1use 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;
36const FIRST_ORDER: usize = 8;
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40struct Pointer {
41 offset: u64,
42 order: u8,
43 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 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 if let Some(bytes) = node.inline_value(index) {
299 V::BOUND.check(bytes);
300 Ok(Some(V::from_bytes(Cow::Borrowed(bytes))))
301 } else {
302 let value = node.value(index);
303 drop(node);
306 decode(self.value(value)?).map(Some)
307 }
308 }
309 pub fn contains_key(&self, key: &K) -> Result<bool> {
310 Ok(self.find(key)?.is_some())
311 }
312 pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>> {
313 self.healthy()?;
314 let key_bytes = key.to_bytes().into_owned();
315 K::BOUND.check(&key_bytes);
316 let bytes = value.into_bytes();
317 V::BOUND.check(&bytes);
318 let mut tx = Transaction::new(self);
319 let (top, split, old) = tx.insert(tx.root.top, &key, key_bytes, bytes, 0)?;
320 tx.root.top = Some(if let Some((entry, right)) = split {
321 tx.save(
322 None,
323 &Node {
324 entries: vec![entry],
325 children: vec![top, right],
326 },
327 )?
328 } else {
329 top
330 });
331 drop(key);
332 let old = old.map(decode).transpose()?;
333 tx.commit()?;
334 Ok(old)
335 }
336 pub fn remove(&mut self, key: &K) -> Result<Option<V>> {
337 self.healthy()?;
338 let mut tx = Transaction::new(self);
339 let old = tx.remove_key(key)?;
340 let value = old.map(decode).transpose()?;
341 tx.commit()?;
342 Ok(value)
343 }
344 pub fn remove_many(&mut self, keys: std::collections::BTreeSet<K>) -> Result<u64> {
345 self.healthy()?;
346 let mut removed = 0;
347 let mut keys = keys.into_iter().peekable();
348 while keys.peek().is_some() {
349 let mut tx = Transaction::new(self);
350 for key in keys.by_ref().take(32) {
351 removed += u64::from(tx.remove_key(&key)?.is_some());
352 }
353 tx.commit()?;
354 }
355 Ok(removed)
356 }
357 pub fn clear(&mut self) -> Result<()> {
358 self.healthy()?;
359 let mut tx = Transaction::new(self);
360 tx.root.top = None;
361 tx.root.length = 0;
362 tx.root.cursor = record::HEADER_BYTES;
363 tx.root.free.fill(None);
364 tx.commit()
365 }
366 fn seek_path(&self, bound: &Bound<K>, forward: bool) -> Result<Vec<Frame>> {
367 self.healthy()?;
368 let mut path = Vec::new();
369 let mut pointer = self.root.borrow().top;
370 while let Some(p) = pointer {
371 ensure(
372 path.len() < MAX_DEPTH,
373 Error::Corrupt("map cursor exceeds height bound"),
374 )?;
375 let node = self.read_node(p, path.len())?;
376 let index = match bound {
377 Bound::Unbounded => {
378 if forward {
379 0
380 } else {
381 node.len()
382 }
383 }
384 Bound::Included(k) => match node.search(k)? {
385 Ok(i) => {
386 if forward {
387 i
388 } else {
389 i + 1
390 }
391 }
392 Err(i) => i,
393 },
394 Bound::Excluded(k) => match node.search(k)? {
395 Ok(i) => {
396 if forward {
397 i + 1
398 } else {
399 i
400 }
401 }
402 Err(i) => i,
403 },
404 };
405 pointer = node.children.get(index).copied();
406 path.push(Frame {
407 node,
408 index,
409 descend: false,
410 });
411 }
412 Ok(path)
413 }
414 fn advance_path(
415 &self,
416 path: &mut Vec<Frame>,
417 forward: bool,
418 keys_only: bool,
419 ) -> Result<Option<(K, Option<Value>)>> {
420 self.healthy()?;
421 while let Some(frame) = path.last_mut() {
422 if frame.descend {
423 frame.descend = false;
424 let mut child = frame.node.children.get(frame.index).copied();
425 while let Some(p) = child {
426 ensure(
427 path.len() < MAX_DEPTH,
428 Error::Corrupt("map cursor exceeds height bound"),
429 )?;
430 let node = self.read_node(p, path.len())?;
431 let index = if forward { 0 } else { node.len() };
432 child = node.children.get(index).copied();
433 path.push(Frame {
434 node,
435 index,
436 descend: false,
437 });
438 }
439 continue;
440 }
441 let index = if forward {
442 frame.index
443 } else {
444 if frame.index == 0 {
445 path.pop();
446 continue;
447 }
448 frame.index - 1
449 };
450 if index >= frame.node.len() {
451 path.pop();
452 continue;
453 }
454 let bytes = frame.node.key_bytes(index);
455 K::BOUND.check(bytes);
456 let key = K::from_bytes(Cow::Borrowed(bytes));
457 let value = (!keys_only).then(|| frame.node.value(index));
458 frame.index = if forward { index + 1 } else { index };
459 frame.descend = !frame.node.children.is_empty();
462 return Ok(Some((key, value)));
463 }
464 Ok(None)
465 }
466 pub fn range(&self, bounds: impl RangeBounds<K>) -> TreeIter<'_, K, V, M> {
467 let lower = bounds.start_bound().cloned();
468 let upper = bounds.end_bound().cloned();
469 let invalid = match (&lower, &upper) {
470 (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => {
471 a > b
472 || (a == b
473 && matches!((&lower, &upper), (Bound::Excluded(_), Bound::Excluded(_))))
474 }
475 _ => false,
476 };
477 TreeIter {
478 tree: self,
479 lower,
480 upper,
481 front: None,
482 back: None,
483 exhausted: false,
484 invalid,
485 keys_only: false,
486 }
487 }
488 pub fn keys_range(
489 &self,
490 bounds: impl RangeBounds<K>,
491 ) -> impl DoubleEndedIterator<Item = K> + '_ {
492 let mut iter = self.range(bounds);
493 iter.keys_only = true;
494 iter.map(MapEntry::into_key)
495 }
496}
497struct Frame {
498 node: Rc<ReadNode>,
499 index: usize,
500 descend: bool,
501}
502fn decode<T: Storable>(bytes: Vec<u8>) -> Result<T> {
503 T::BOUND.check(&bytes);
504 Ok(T::from_bytes(Cow::Owned(bytes)))
505}
506
507type Split = Option<(Entry, Pointer)>;
508struct Transaction<'a, K, V, M: Memory> {
509 tree: &'a Tree<K, V, M>,
510 root: Root,
511 writes: BTreeMap<u64, Vec<u8>>,
512}
513impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> Transaction<'a, K, V, M> {
514 fn new(tree: &'a Tree<K, V, M>) -> Self {
515 Self {
516 tree,
517 root: tree.root.borrow().clone(),
518 writes: BTreeMap::new(),
519 }
520 }
521 fn remove_key(&mut self, key: &K) -> Result<Option<Vec<u8>>> {
522 let Some(top) = self.root.top else {
523 return Ok(None);
524 };
525 let (changed, old) = self.remove(top, key, 0)?;
526 let Some(old) = old else { return Ok(None) };
527
528 if let Some(node) = changed {
529 self.root.top = if node.entries.is_empty() {
530 self.free(top)?;
531 node.children.first().copied()
532 } else {
533 Some(self.save(Some(top), &node)?)
534 };
535 }
536 self.root.length -= 1;
537 Ok(Some(old))
538 }
539 fn bytes(&self, p: Pointer, magic: [u8; 8]) -> Result<Vec<u8>> {
540 p.check(self.root.cursor)?;
541 if let Some(bytes) = self.writes.get(&p.offset) {
542 Ok(bytes.clone())
543 } else {
544 record::read_bytes(&self.tree.memory, p.offset, p.capacity(), magic)
545 }
546 }
547 fn node(&self, p: Pointer, depth: usize) -> Result<Node> {
548 Ok(self.read_node(p, depth)?.owned())
549 }
550 fn read_node(&self, p: Pointer, depth: usize) -> Result<Rc<ReadNode>> {
551 if let Some(bytes) = self.writes.get(&p.offset) {
552 Ok(Rc::new(ReadNode::decode::<K, V>(
553 bytes.clone(),
554 self.root.cursor,
555 p.unit,
556 )?))
557 } else {
558 self.tree.read_node(p, depth)
559 }
560 }
561 fn value(&self, v: &Value) -> Result<Vec<u8>> {
562 let bytes = match v {
563 Value::Inline(b) => b.clone(),
564 Value::External(p) => {
565 p.check(self.root.cursor)?;
566 if let Some(bytes) = self.writes.get(&p.offset) {
567 record::decode_payload(VALUE, bytes)?.to_vec()
568 } else {
569 record::read_payload(&self.tree.memory, p.offset, p.capacity(), VALUE)?
570 }
571 }
572 };
573 V::BOUND.check(&bytes);
574 Ok(bytes)
575 }
576 fn free(&mut self, p: Pointer) -> Result<()> {
577 let index = usize::from(p.order);
578 self.writes.insert(
579 p.offset,
580 record::encode_payload(FREE, &link_bytes(self.root.free[index]))?,
581 );
582 self.root.free[index] = Some(p);
583 Ok(())
584 }
585 fn allocate(&mut self, order: usize) -> Result<Pointer> {
586 ensure(order < BINS, Error::Budget)?;
587 for bin in order..BINS {
588 if let Some(mut p) = self.root.free[bin] {
589 let next: Option<Pointer> = decode_link(
590 record::decode_payload(FREE, &self.bytes(p, FREE)?)?,
591 self.root.cursor,
592 p.unit,
593 )?;
594 if let Some(next) = next {
595 next.check(self.root.cursor)?;
596 ensure(
597 next.order == p.order && next != p,
598 Error::Corrupt("map free-list link"),
599 )?;
600 }
601 self.root.free[bin] = next;
602 while usize::from(p.order) > order {
605 p.order -= 1;
606 let sibling = Pointer {
607 offset: p.offset + p.capacity(),
608 ..p
609 };
610 self.free(sibling)?;
611 }
612 return Ok(p);
613 }
614 }
615 let p = Pointer {
616 offset: self.root.cursor,
617 order: u8::try_from(order).unwrap(),
618 unit: self.root.options.allocation_unit_bytes,
619 };
620 self.root.cursor = self
621 .root
622 .cursor
623 .checked_add(p.capacity())
624 .ok_or(Error::Budget)?;
625 Ok(p)
626 }
627 fn save_bytes(
628 &mut self,
629 previous: Option<Pointer>,
630 bytes: Vec<u8>,
631 minimum: usize,
632 ) -> Result<Pointer> {
633 let allocation_len = bytes.len().max(minimum);
634 let units = allocation_len.div_ceil(usize::from(self.root.options.allocation_unit_bytes));
635 let order = FIRST_ORDER + units.next_power_of_two().trailing_zeros() as usize;
636 let p = if let Some(p) = previous.filter(|p| p.capacity() >= allocation_len as u64) {
637 let smaller_available =
641 (order..usize::from(p.order)).any(|order| self.root.free[order].is_some());
642 if usize::from(p.order) >= order + 2 && smaller_available {
643 let smaller = self.allocate(order)?;
644 self.free(p)?;
645 smaller
646 } else {
647 p
648 }
649 } else {
650 if let Some(p) = previous {
651 self.free(p)?;
652 }
653 self.allocate(order)?
654 };
655 self.writes.insert(p.offset, bytes);
656 Ok(p)
657 }
658 fn save(&mut self, p: Option<Pointer>, node: &Node) -> Result<Pointer> {
659 self.save_node_bytes(p, node.encode()?)
660 }
661 fn save_node_bytes(&mut self, p: Option<Pointer>, bytes: Vec<u8>) -> Result<Pointer> {
662 let target = self.root.options.node_target_bytes;
663 let minimum = match (record::bound::<K>(), record::bound::<V>()) {
664 (Some((key, _)), Some((value, fixed))) => {
665 let value_bytes = if fixed && value > INLINE as u32 {
668 9 } else {
670 u64::from(value).min(INLINE as u64)
671 };
672 let full_node = record::PREFIX as u64
673 + 2
674 + (MAX_ENTRIES as u64 + 1) * 9
675 + MAX_ENTRIES as u64 * (5 + u64::from(key) + value_bytes);
676 (full_node * 3 / 4).min(u64::from(target)) as usize
678 }
679 _ => usize::from(target),
680 };
681 self.save_bytes(p, bytes, minimum)
682 }
683 fn save_value(&mut self, previous: Option<&Value>, bytes: Vec<u8>) -> Result<Value> {
684 let old = match previous {
685 Some(Value::External(p)) => Some(*p),
686 _ => None,
687 };
688 if bytes.len() <= INLINE {
689 if let Some(p) = old {
690 self.free(p)?;
691 }
692 Ok(Value::Inline(bytes))
693 } else {
694 Ok(Value::External(self.save_bytes(
695 old,
696 record::encode_payload(VALUE, &bytes)?,
697 0,
698 )?))
699 }
700 }
701 fn insert(
702 &mut self,
703 p: Option<Pointer>,
704 key: &K,
705 key_bytes: Vec<u8>,
706 bytes: Vec<u8>,
707 depth: usize,
708 ) -> Result<(Pointer, Split, Option<Vec<u8>>)> {
709 ensure(
710 depth < MAX_DEPTH,
711 Error::Corrupt("map path exceeds height bound"),
712 )?;
713 let read = p.map(|p| self.read_node(p, depth)).transpose()?;
714 let search = read.as_ref().map_or(Ok(Err(0)), |node| node.search(key))?;
715 let (mut node, old) = match search {
716 Ok(i) => {
717 let read = read.as_ref().unwrap();
718 let previous = read.value(i);
719 let old = self.value(&previous)?;
720 let value = self.save_value(Some(&previous), bytes)?;
721 let same_pointer =
722 matches!((&previous,&value),(Value::External(a),Value::External(b)) if a==b);
723 if same_pointer {
724 return Ok((p.unwrap(), None, Some(old)));
725 }
726 if let (Value::Inline(_), Value::Inline(bytes)) = (&previous, &value) {
727 let next = self.save_node_bytes(p, read.replace_inline(i, bytes)?)?;
728 return Ok((next, None, Some(old)));
729 }
730 let mut node = read.owned();
731 node.entries[i].value = value;
732 (node, Some(old))
733 }
734 Err(i) => {
735 if let Some(child) = read.as_ref().and_then(|node| node.children.get(i)).copied() {
736 let (next, split, old) =
737 self.insert(Some(child), key, key_bytes, bytes, depth + 1)?;
738 if split.is_none() && next == child {
739 return Ok((p.unwrap(), None, old));
740 }
741 let mut node = read.as_ref().unwrap().owned();
742 node.children[i] = next;
743 if let Some((entry, right)) = split {
744 node.entries.insert(i, entry);
745 node.children.insert(i + 1, right);
746 }
747 (node, old)
748 } else {
749 let value = self.save_value(None, bytes)?;
750 let mut node = read
751 .as_ref()
752 .map_or_else(Node::default, |node| node.owned());
753 node.entries.insert(
754 i,
755 Entry {
756 key: key_bytes,
757 value,
758 },
759 );
760 self.root.length = self.root.length.checked_add(1).ok_or(Error::Budget)?;
761 (node, None)
762 }
763 }
764 };
765 let split = if node.entries.len() > MAX_ENTRIES {
766 let right_entries = node.entries.split_off(DEGREE + 1);
767 let median = node.entries.pop().unwrap();
768 let children = if node.children.is_empty() {
769 vec![]
770 } else {
771 node.children.split_off(DEGREE + 1)
772 };
773 let right = self.save(
774 None,
775 &Node {
776 entries: right_entries,
777 children,
778 },
779 )?;
780 Some((median, right))
781 } else {
782 None
783 };
784 Ok((self.save(p, &node)?, split, old))
785 }
786 fn remove(
789 &mut self,
790 p: Pointer,
791 key: &K,
792 depth: usize,
793 ) -> Result<(Option<Node>, Option<Vec<u8>>)> {
794 ensure(
795 depth < MAX_DEPTH,
796 Error::Corrupt("map path exceeds height bound"),
797 )?;
798 let read = self.read_node(p, depth)?;
799 match read.search(key)? {
800 Ok(i) => {
801 let mut node = read.owned();
802 let old = self.value(&node.entries[i].value)?;
803 if let Value::External(p) = node.entries[i].value {
804 self.free(p)?;
805 }
806 if node.children.is_empty() {
807 node.entries.remove(i);
808 } else {
809 let child_pointer = node.children[i + 1];
810 let (child, entry) = self.extract_min(child_pointer, depth + 1)?;
811 node.entries[i] = entry;
812 if let Some(child) = child {
813 self.finish_child(&mut node, i + 1, child, depth)?;
814 }
815 }
816 Ok((Some(node), Some(old)))
817 }
818 Err(i) => {
819 let Some(child_pointer) = read.children.get(i).copied() else {
820 return Ok((None, None));
821 };
822 let (child, old) = self.remove(child_pointer, key, depth + 1)?;
823 let node = child
824 .map(|child| self.changed_parent(&read, i, child, depth))
825 .transpose()?
826 .flatten();
827 Ok((node, old))
828 }
829 }
830 }
831 fn extract_min(&mut self, p: Pointer, depth: usize) -> Result<(Option<Node>, Entry)> {
832 ensure(
833 depth < MAX_DEPTH,
834 Error::Corrupt("map path exceeds height bound"),
835 )?;
836 let read = self.read_node(p, depth)?;
837 ensure(read.len() != 0, Error::Corrupt("empty successor node"))?;
838 if read.children.is_empty() {
839 let mut node = read.owned();
840 let entry = node.entries.remove(0);
841 Ok((Some(node), entry))
842 } else {
843 let (child, entry) = self.extract_min(read.children[0], depth + 1)?;
844 let node = child
845 .map(|child| self.changed_parent(&read, 0, child, depth))
846 .transpose()?
847 .flatten();
848 Ok((node, entry))
849 }
850 }
851 fn changed_parent(
854 &mut self,
855 read: &ReadNode,
856 i: usize,
857 child: Node,
858 depth: usize,
859 ) -> Result<Option<Node>> {
860 if child.entries.len() >= MIN_ENTRIES {
861 let previous = read.children[i];
862 let next = self.save(Some(previous), &child)?;
863 if next == previous {
864 return Ok(None);
865 }
866 let mut parent = read.owned();
867 parent.children[i] = next;
868 Ok(Some(parent))
869 } else {
870 let mut parent = read.owned();
871 self.rebalance(&mut parent, i, child, depth)?;
872 Ok(Some(parent))
873 }
874 }
875 fn finish_child(
876 &mut self,
877 parent: &mut Node,
878 i: usize,
879 child: Node,
880 depth: usize,
881 ) -> Result<()> {
882 if child.entries.len() >= MIN_ENTRIES {
883 parent.children[i] = self.save(Some(parent.children[i]), &child)?;
884 Ok(())
885 } else {
886 self.rebalance(parent, i, child, depth)
887 }
888 }
889 fn rebalance(
890 &mut self,
891 parent: &mut Node,
892 i: usize,
893 mut child: Node,
894 parent_depth: usize,
895 ) -> Result<()> {
896 let depth = parent_depth + 1;
897 let p = parent.children[i];
898 let mut left = if i > 0 {
899 Some(self.node(parent.children[i - 1], depth)?)
900 } else {
901 None
902 };
903 if let Some(left) = &mut left {
904 ensure(
905 left.children.is_empty() == child.children.is_empty(),
906 Error::Corrupt("B-tree sibling levels"),
907 )?;
908 if left.entries.len() > MIN_ENTRIES {
909 child.entries.insert(
910 0,
911 std::mem::replace(&mut parent.entries[i - 1], left.entries.pop().unwrap()),
912 );
913 if let Some(p) = left.children.pop() {
914 child.children.insert(0, p);
915 }
916 parent.children[i - 1] = self.save(Some(parent.children[i - 1]), left)?;
917 parent.children[i] = self.save(Some(p), &child)?;
918 return Ok(());
919 }
920 }
921 let mut right = if i + 1 < parent.children.len() {
922 Some(self.node(parent.children[i + 1], depth)?)
923 } else {
924 None
925 };
926 if let Some(right) = &mut right {
927 ensure(
928 right.children.is_empty() == child.children.is_empty(),
929 Error::Corrupt("B-tree sibling levels"),
930 )?;
931 if right.entries.len() > MIN_ENTRIES {
932 child.entries.push(std::mem::replace(
933 &mut parent.entries[i],
934 right.entries.remove(0),
935 ));
936 if !right.children.is_empty() {
937 child.children.push(right.children.remove(0));
938 }
939 parent.children[i + 1] = self.save(Some(parent.children[i + 1]), right)?;
940 parent.children[i] = self.save(Some(p), &child)?;
941 return Ok(());
942 }
943 }
944 let (left_index, mut left, right) = if let Some(left) = left {
945 (i - 1, left, child)
946 } else {
947 (
948 i,
949 child,
950 right.ok_or(Error::Corrupt("B-tree missing separator"))?,
951 )
952 };
953 ensure(
954 left_index < parent.entries.len(),
955 Error::Corrupt("B-tree missing separator"),
956 )?;
957 let left_p = parent.children[left_index];
958 let right_p = parent.children[left_index + 1];
959 left.entries.push(parent.entries.remove(left_index));
960 left.entries.extend(right.entries);
961 left.children.extend(right.children);
962 self.free(right_p)?;
963 parent.children[left_index] = self.save(Some(left_p), &left)?;
964 parent.children.remove(left_index + 1);
965 Ok(())
966 }
967 fn commit(self) -> Result<()> {
968 let changed = self.root != *self.tree.root.borrow();
969 let header = if changed {
970 Some(self.root.encode()?)
971 } else {
972 None
973 };
974 if let Some(h) = &header {
975 ensure(h.len() as u64 <= record::HEADER_BYTES, Error::Budget)?;
976 }
977 record::reserve(&self.tree.memory, self.root.cursor)?;
978 self.tree.poisoned.set(true);
979
980 for (offset, bytes) in self.writes {
981 self.tree.memory.write(offset, &bytes);
982 }
983 if let Some(h) = header {
984 self.tree.memory.write(0, &h);
985 }
986 *self.tree.root.borrow_mut() = self.root;
987 self.tree.poisoned.set(false);
988 Ok(())
989 }
990}
991pub struct MapEntry<K, V> {
997 key: K,
998 bytes: Vec<u8>,
999 value: PhantomData<V>,
1000}
1001impl<K, V: Storable> MapEntry<K, V> {
1002 pub const fn key(&self) -> &K {
1004 &self.key
1005 }
1006 pub fn value(&self) -> V {
1011 V::BOUND.check(&self.bytes);
1012 V::from_bytes(Cow::Borrowed(&self.bytes))
1013 }
1014 pub fn into_pair(self) -> (K, V) {
1019 (self.key, decode(self.bytes).expect("invalid map value"))
1020 }
1021 pub fn into_key(self) -> K {
1023 self.key
1024 }
1025 pub fn into_value(self) -> V {
1030 decode(self.bytes).expect("invalid map value")
1031 }
1032}
1033
1034pub struct TreeIter<'a, K, V, M: Memory> {
1041 tree: &'a Tree<K, V, M>,
1042 lower: Bound<K>,
1043 upper: Bound<K>,
1044 front: Option<Vec<Frame>>,
1045 back: Option<Vec<Frame>>,
1046 exhausted: bool,
1047 invalid: bool,
1048 keys_only: bool,
1049}
1050impl<K: Storable + Ord + Clone, V: Storable, M: Memory> TreeIter<'_, K, V, M> {
1051 fn step(&mut self, forward: bool) -> Result<Option<MapEntry<K, V>>> {
1052 ensure(!self.invalid, Error::Bounds)?;
1053 self.tree.healthy()?;
1054 let empty = match (&self.lower, &self.upper) {
1055 (Bound::Included(a), Bound::Included(b)) => a > b,
1056 (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => {
1057 a >= b
1058 }
1059 _ => false,
1060 };
1061 if empty {
1062 return Ok(None);
1063 }
1064 let (path, bound) = if forward {
1065 (&mut self.front, &self.lower)
1066 } else {
1067 (&mut self.back, &self.upper)
1068 };
1069 if path.is_none() {
1070 *path = Some(self.tree.seek_path(bound, forward)?);
1071 }
1072 let entry = self
1073 .tree
1074 .advance_path(path.as_mut().unwrap(), forward, self.keys_only)?;
1075 if let Some((key, value)) = entry {
1076 let after = match &self.lower {
1077 Bound::Unbounded => true,
1078 Bound::Included(k) => key >= *k,
1079 Bound::Excluded(k) => key > *k,
1080 };
1081 let before = match &self.upper {
1082 Bound::Unbounded => true,
1083 Bound::Included(k) => key <= *k,
1084 Bound::Excluded(k) => key < *k,
1085 };
1086 ensure(
1087 if forward { after } else { before },
1088 Error::Corrupt("map cursor key order"),
1089 )?;
1090 if !(after && before) {
1091 return Ok(None);
1092 }
1093 if forward {
1094 self.lower = Bound::Excluded(key.clone());
1095 } else {
1096 self.upper = Bound::Excluded(key.clone());
1097 }
1098 return Ok(Some(MapEntry {
1099 key,
1100 bytes: value
1101 .map(|value| self.tree.value(value))
1102 .transpose()?
1103 .unwrap_or_default(),
1104 value: PhantomData,
1105 }));
1106 }
1107 Ok(None)
1108 }
1109 fn advance(&mut self, forward: bool) -> Option<Result<MapEntry<K, V>>> {
1110 if self.exhausted {
1111 return None;
1112 }
1113 match self.step(forward) {
1114 Ok(Some(entry)) => Some(Ok(entry)),
1115 Ok(None) => {
1116 self.exhausted = true;
1117 None
1118 }
1119 Err(error) => {
1120 self.exhausted = true;
1121 Some(Err(error))
1122 }
1123 }
1124 }
1125}
1126impl<K: Storable + Ord + Clone, V: Storable, M: Memory> Iterator for TreeIter<'_, K, V, M> {
1127 type Item = MapEntry<K, V>;
1128 fn next(&mut self) -> Option<Self::Item> {
1129 self.advance(true)
1130 .map(|entry| entry.expect("invalid map entry"))
1131 }
1132}
1133impl<K: Storable + Ord + Clone, V: Storable, M: Memory> DoubleEndedIterator
1134 for TreeIter<'_, K, V, M>
1135{
1136 fn next_back(&mut self) -> Option<Self::Item> {
1137 self.advance(false)
1138 .map(|entry| entry.expect("invalid map entry"))
1139 }
1140}
1141impl<K: Storable + Ord + Clone, V: Storable, M: Memory> std::iter::FusedIterator
1142 for TreeIter<'_, K, V, M>
1143{
1144}