reddb-io-engine 1.46.2

Shared RedDB query execution and storage primitives for native and WebAssembly runtimes.
Documentation
//! An immutable vocabulary and every offset into it share one leaf image.
//! Splits, merges and compaction unpack records before interning them in the
//! destination leaf. Logical WAL, replication and cursors see portable RER2.
use super::*;
use reddb_file::btree_value_layout::{btree_reference_parts, BTREE_REFERENCE_VOCABULARY};
use std::{borrow::Cow, collections::HashMap};

fn corrupt() -> BTreeError {
    BTreeError::Corrupted("invalid leaf reference vocabulary".into())
}

fn entry(page: &Page, at: usize) -> BTreeResult<(usize, &[u8])> {
    let head = (page.right_child() & 0xffff) as usize;
    if head == 0 || at < head || at < leaf_cells_start(page) || at < leaf_slots_end(page) {
        return Err(corrupt());
    }
    let bytes = page.as_bytes().get(at..).ok_or_else(corrupt)?;
    let header = bytes.get(..3).ok_or_else(corrupt)?;
    let next = usize::from(u16::from_le_bytes([header[0], header[1]]));
    let len = usize::from(header[2]);
    if !(1..128).contains(&len) || (next != 0 && next < at + 3 + len) {
        return Err(corrupt());
    }
    Ok((next, bytes.get(2..3 + len).ok_or_else(corrupt)?))
}

// On a leaf the low half of right_child is the dictionary head. The high
// half is a lower bound on live cell/slot bytes. Records already on a leaf
// when its first dictionary entry arrives need not be scanned to initialize it.
pub(super) fn live_bound(page: &Page) -> usize {
    (page.right_child() >> 16) as usize
}

/// Count each live vocabulary once without expanding any record. A leaf can
/// retain orphaned entries after deletes, so the linked list alone overcounts.
pub(super) fn full_enough(page: &Page, minimum: usize) -> BTreeResult<bool> {
    if page.right_child() == 0 {
        return Ok(leaf_used_bytes(page)? >= minimum);
    }
    if live_bound(page) >= minimum {
        return Ok(true);
    }
    let mut seen = [0u64; PAGE_SIZE.div_ceil(64)];
    let mut used = 0;
    for i in 0..usize::from(page.cell_count()) {
        let (key, value) = read_leaf_cell_borrowed(page, i)?;
        used += 6 + key.len() + value.len();
        if shared(value) {
            let offset = value.get(1..3).ok_or_else(corrupt)?;
            let at = usize::from(u16::from_le_bytes([offset[0], offset[1]]));
            let word = seen.get_mut(at / 64).ok_or_else(corrupt)?;
            let bit = 1 << (at % 64);
            if *word & bit == 0 {
                used += entry(page, at)?.1.len() + 2;
                *word |= bit;
            }
        }
        if used >= minimum {
            return Ok(true);
        }
    }
    Ok(false)
}
pub(super) fn account_insert(page: &mut Page, bytes: usize) {
    if page.right_child() != 0 {
        let live = (live_bound(page) + bytes).min(PAGE_SIZE);
        page.set_right_child((page.right_child() & 0xffff) | ((live as u32) << 16));
    }
}
pub(super) fn account_removal(page: &mut Page, bytes: usize) {
    if page.right_child() != 0 {
        let live = live_bound(page).saturating_sub(bytes);
        page.set_right_child((page.right_child() & 0xffff) | ((live as u32) << 16));
    }
}

fn lookup(page: &Page, names: &[u8]) -> BTreeResult<Option<u16>> {
    let mut at = (page.right_child() & 0xffff) as usize;
    while at != 0 {
        let (next, stored) = entry(page, at)?;
        if stored == names {
            return Ok(Some(at as u16));
        }
        at = next;
    }
    Ok(None)
}

fn packed(at: u16, body: &[u8]) -> Vec<u8> {
    let mut buf = Vec::with_capacity(3 + body.len());
    buf.push(BTREE_REFERENCE_VOCABULARY);
    buf.extend_from_slice(&at.to_le_bytes());
    buf.extend_from_slice(body);
    buf
}

pub(super) enum Cell<'a> {
    Inline(&'a [u8]),
    Reference(u16, &'a [u8]),
}
impl Cell<'_> {
    pub fn len(&self) -> usize {
        match self {
            Self::Inline(b) => b.len(),
            Self::Reference(_, b) => 3 + b.len(),
        }
    }
    pub fn write(&self, out: &mut [u8]) {
        match self {
            Self::Inline(bytes) => out.copy_from_slice(bytes),
            Self::Reference(at, body) => {
                out[0] = BTREE_REFERENCE_VOCABULARY;
                out[1..3].copy_from_slice(&at.to_le_bytes());
                out[3..].copy_from_slice(body);
            }
        }
    }
}

pub(super) fn pack<'a>(
    page: &mut Page,
    value: &'a [u8],
    cache: Option<&mut HashMap<&'a [u8], u16>>,
) -> BTreeResult<Cell<'a>> {
    let Some((names, body)) = btree_reference_parts(value) else {
        return Ok(Cell::Inline(value));
    };
    let found = match cache.as_ref() {
        Some(cache) => cache.get(names).copied(),
        None => lookup(page, names)?,
    };
    let at = if let Some(at) = found {
        at
    } else {
        let used = names.len() + 2;
        if leaf_free_bytes(page) < used {
            return Err(corrupt());
        }
        let at = leaf_cells_start(page) - used;
        let prev = page.right_child() as u16;
        let bytes = page.as_bytes_mut();
        bytes[at..at + 2].copy_from_slice(&prev.to_le_bytes());
        bytes[at + 2..at + used].copy_from_slice(names);
        page.set_free_end(at as u16);
        page.set_right_child((page.right_child() & 0xffff0000) | at as u32);
        if let Some(cache) = cache {
            cache.insert(names, at as u16);
        }
        at as u16
    };
    Ok(Cell::Reference(at, body))
}

pub(super) fn pack_existing<'a>(page: &Page, value: &'a [u8]) -> BTreeResult<Cow<'a, [u8]>> {
    if let Some((names, body)) = btree_reference_parts(value) {
        if let Some(at) = lookup(page, names)? {
            return Ok(Cow::Owned(packed(at, body)));
        }
    }
    Ok(Cow::Borrowed(value))
}

/// Reconstitute the exact caller bytes, charging the expanded length before
/// allocating. Key-only probes never call this function.
pub(super) fn expand(
    page: &Page,
    value: &[u8],
    include_flag: bool,
    limit: usize,
) -> BTreeResult<Vec<u8>> {
    let offset = value.get(1..3).ok_or_else(corrupt)?;
    let at = u16::from_le_bytes([offset[0], offset[1]]);
    let (_, names) = entry(page, usize::from(at))?;
    let size = usize::from(include_flag) + 4 + names.len() + value.len() - 3;
    if size > limit {
        return Err(value_layout::ValueLayoutError::ReadLimitExceeded {
            required_bytes: size,
            limit_bytes: limit,
        }
        .into());
    }
    let mut out = Vec::with_capacity(size);
    if include_flag {
        out.push(0);
    }
    out.extend_from_slice(b"RER2");
    out.extend_from_slice(names);
    out.extend_from_slice(&value[3..]);
    Ok(out)
}

pub(super) fn shared(stored: &[u8]) -> bool {
    stored.first() == Some(&BTREE_REFERENCE_VOCABULARY)
}

/// Exact footprint of a freshly packed subset, including its distinct
/// vocabulary entries. Used for split and sibling redistribution decisions.
#[derive(Default)]
pub(super) struct Occupancy<'a> {
    pub bytes: usize,
    names: HashMap<&'a [u8], usize>,
}
impl<'a> Occupancy<'a> {
    pub fn from_entries(entries: &'a [(Vec<u8>, Vec<u8>)]) -> Self {
        let mut used = Self::default();
        for e in entries {
            used.add(e);
        }
        used
    }
    pub fn add(&mut self, e: &'a (Vec<u8>, Vec<u8>)) {
        self.bytes += leaf_entry_size(e);
        if let Some((names, _)) = btree_reference_parts(&e.1) {
            let count = self.names.entry(names).or_default();
            if *count != 0 {
                self.bytes -= names.len() + 2;
            }
            *count += 1;
        }
    }
    pub fn remove(&mut self, e: &'a (Vec<u8>, Vec<u8>)) {
        let mut freed = leaf_entry_size(e);
        if let Some((names, _)) = btree_reference_parts(&e.1) {
            let count = self
                .names
                .get_mut(names)
                .expect("removing an occupied vocabulary");
            *count -= 1;
            if *count != 0 {
                freed -= names.len() + 2;
            }
        }
        self.bytes -= freed;
    }
}
pub(super) fn borrow_count<'a>(
    receiver: &'a [(Vec<u8>, Vec<u8>)],
    donor: &'a [(Vec<u8>, Vec<u8>)],
    order: impl Iterator<Item = &'a (Vec<u8>, Vec<u8>)>,
    minimum: usize,
) -> usize {
    let mut dst = Occupancy::from_entries(receiver);
    let mut src = Occupancy::from_entries(donor);
    let mut count = 0;
    for entry in order {
        let before = dst.bytes;
        dst.add(entry);
        src.remove(entry);
        if src.bytes < minimum
            || dst.bytes > PAGE_SIZE - LEAF_SLOT_ARRAY_OFFSET
            || (before >= minimum && dst.bytes > src.bytes)
        {
            break;
        }
        count += 1;
    }
    count
}