moonseed 0.2.0

Deterministic, checkpointable Lua 5.4 runtime in safe Rust
Documentation
//! Bounded host-owned raw traversal. No guest callbacks or bulk table copies.
use super::{ApiError, NativeContext, Result, Table, Value};

/// Shared bounds for a host conversion, including nested tables and cycles.
/// Pass the same budget to every cursor; pass depth 0 for the root and increase
/// it for each child. Detect cycles by `Table::id` when the output forbids them.
/// These are host policy, not snapshot state or a guest allocation allowance.
#[derive(Debug)]
pub struct TraversalBudget {
    pub(crate) entries: usize,
    pub(crate) bytes: usize,
    pub(crate) steps: usize,
    pub(crate) max_depth: usize,
}

impl TraversalBudget {
    /// Bound total returned pairs, total payload bytes, visited slots (including
    /// deleted anchors), and nesting depth (root is 0, exclusive upper bound).
    /// Each pair costs 256 payload bytes plus the key/value string lengths.
    /// This bounds output/root counts; actual host allocator overhead is separate.
    pub fn new(entries: usize, bytes: usize, steps: usize, max_depth: usize) -> Self {
        Self {
            entries,
            bytes,
            steps,
            max_depth,
        }
    }
}

/// A host cursor over raw table slots in the configured iteration profile.
/// Holds one existing root; each returned object is rooted separately. Drop pairs as consumed to
/// keep temporary roots constant. Mutation during traversal may skip/revisit
/// entries; budgets still apply. Does not invoke `__pairs` or `__index`.
#[derive(Debug)]
pub struct TableTraversal {
    pub(crate) table: Table,
    pub(crate) slot: usize,
    pub(crate) depth: usize,
    pub(crate) previous: Option<crate::table::TableKey>,
    pub(crate) finished: bool,
}

impl TableTraversal {
    /// Read one raw pair. A shared budget limits total visits and returned
    /// payload, including revisits from cycles. Each visited slot costs one VM
    /// fuel unit; the hard runtime fuel limit is checked before work. A native
    /// callback cannot pause. Insertion order may overrun its quantum by at most
    /// the supplied step budget; Sorted also prepays string-byte fuel (ADR 0061).
    /// Budget exhaustion is `ApiError::TraversalLimit`,
    /// never successful end-of-table. The sorted profile visits all stored slots
    /// per call (including the final call), and retains an owned primitive
    /// control key; string control keys copy their bytes. Insertion order
    /// copies no strings or table contents.
    pub fn next(
        &mut self,
        cx: &mut NativeContext<'_>,
        budget: &mut TraversalBudget,
    ) -> Result<Option<(Value, Value)>> {
        if self.depth >= budget.max_depth {
            return Err(ApiError::TraversalLimit.into());
        }
        cx.runtime.api_traversal_next(self, budget)
    }
}