qubit-json 0.13.0

Resource-aware infrastructure for lenient and strict JSON processing
Documentation
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Implements non-recursive, budget-aware mutable JSON tree processing.
//!
//! # Mutable traversal safety
//!
//! Each stack entry owns an iterator whose lifetime borrows one container in
//! the exclusively borrowed root. A yielded child borrow lasts for the tree
//! lifetime, so its descendants can be borrowed while ancestor iterators stay
//! suspended in the stack. Visitors may replace the current value; borrowed
//! container iterators prevent structural changes to ancestors until traversal
//! finishes. No raw pointers or erased lifetimes are needed.

use qubit_budget::ResourceQuantity;
use qubit_budget::json::JsonValueTransaction;
use serde_json::Value;

use super::JsonTreeContext;
use super::JsonTreeControl;
use super::JsonTreeLocation;
use super::JsonTreeMutVisitor;
use super::JsonTreeMutateError;
use super::JsonTreeReader;
use super::internal::MutChildCursor;

/// Mutates a JSON tree between independent input and output transactions.
///
/// The complete original tree is admitted before the first visitor callback.
/// After all callbacks succeed, the complete mutated tree is admitted against
/// the output transaction. Visitor failures and panics can retain partial
/// mutations, while output accounting does not begin until visitor success.
///
/// # Type Parameters
///
/// * `R` - Resource identity shared by the two transactions.
/// * `Q` - Quantity representation shared by the two transactions.
///
/// # Examples
///
/// ```
/// use qubit_budget::json::{JsonResource, JsonValueBudget, JsonValueLimits};
/// use qubit_json::value::traverse::{
///     JsonTreeContext, JsonTreeControl, JsonTreeMutVisitor, JsonTreeMutator,
/// };
/// use serde_json::Value;
///
/// struct Visitor;
/// impl JsonTreeMutVisitor for Visitor {
///     type Error = std::convert::Infallible;
///
///     fn visit(
///         &mut self,
///         _: &mut Value,
///         _: JsonTreeContext<'_>,
///     ) -> Result<JsonTreeControl, Self::Error> {
///         Ok(JsonTreeControl::SkipSubtree)
///     }
/// }
///
/// let limits = JsonValueLimits::<JsonResource, usize>::default();
/// let mut input_budget = JsonValueBudget::new(limits);
/// let mut output_budget = JsonValueBudget::new(limits);
/// let mut input = input_budget.transaction();
/// let mut output = output_budget.transaction();
/// let mut mutator = JsonTreeMutator::new(&mut input, &mut output);
/// let mut value = Value::Null;
/// assert!(mutator.process(&mut value, &mut Visitor).is_ok());
/// ```
pub struct JsonTreeMutator<'input_transaction, 'input_budget, 'output_transaction, 'output_budget, R, Q>
where
    Q: ResourceQuantity,
{
    /// Transaction receiving the complete original-tree charges.
    input: &'input_transaction mut JsonValueTransaction<'input_budget, R, Q>,
    /// Transaction receiving the complete mutated-tree charges.
    output: &'output_transaction mut JsonValueTransaction<'output_budget, R, Q>,
}

impl<'input_transaction, 'input_budget, 'output_transaction, 'output_budget, R, Q>
    JsonTreeMutator<'input_transaction, 'input_budget, 'output_transaction, 'output_budget, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Creates a mutator borrowing independent input and output transactions.
    ///
    /// # Parameters
    ///
    /// * `input` - Transaction receiving charges for the complete original
    ///   tree.
    /// * `output` - Transaction receiving charges for the complete mutated
    ///   tree.
    ///
    /// # Returns
    ///
    /// A mutator borrowing both transactions for its lifetime.
    #[inline(always)]
    #[must_use]
    pub fn new(
        input: &'input_transaction mut JsonValueTransaction<'input_budget, R, Q>,
        output: &'output_transaction mut JsonValueTransaction<'output_budget, R, Q>,
    ) -> Self {
        Self { input, output }
    }

    /// Admits the original tree, mutates it, and admits the final tree.
    ///
    /// Both admissions and all visitor callbacks use explicit stacks rather
    /// than Rust recursion. `SkipSubtree` affects callbacks only; final output
    /// admission always covers every resulting descendant.
    ///
    /// Callbacks may visit descendants added by earlier callbacks. Output
    /// `max_nodes` and `max_depth` are checked only against the complete final
    /// tree; they do not limit callback count or intermediate expansion. A
    /// visitor that adds descendants must bound its own expansion and ensure
    /// traversal terminates. Returning [`JsonTreeControl::SkipSubtree`] skips
    /// descent from the current node, but the final tree is still subject to
    /// output admission. See the
    /// [mutable tree traversal guidance](https://github.com/qubit-ltd/rs-json/blob/main/doc/user_guide.md#read-and-mutate-existing-trees).
    ///
    /// # Type Parameters
    ///
    /// * `V` - Visitor controlling mutations and descendant callbacks.
    ///
    /// # Parameters
    ///
    /// * `root` - Root JSON value to process and mutate.
    /// * `visitor` - Visitor applied after complete input admission.
    ///
    /// # Returns
    ///
    /// `Ok(())` after both complete trees fit and every callback succeeds.
    ///
    /// # Errors
    ///
    /// Returns [`JsonTreeMutateError::InputBudget`] before mutation when the
    /// original tree is rejected, [`JsonTreeMutateError::Visitor`] after a
    /// callback failure, or [`JsonTreeMutateError::OutputBudget`] after a
    /// complete mutation whose result is rejected. Visitor and output failures
    /// retain mutations already made to `root`.
    ///
    /// # Panics
    ///
    /// Propagates a panic from the visitor. Advancing traversal depth panics
    /// only if a materialized tree depth exceeds the range of `usize`.
    pub fn process<V>(&mut self, root: &mut Value, visitor: &mut V) -> Result<(), JsonTreeMutateError<R, Q, V::Error>>
    where
        V: JsonTreeMutVisitor,
    {
        JsonTreeReader::new(&mut *self.input)
            .account(root)
            .map_err(JsonTreeMutateError::InputBudget)?;
        Self::mutate(root, visitor).map_err(JsonTreeMutateError::Visitor)?;
        JsonTreeReader::new(&mut *self.output)
            .account(root)
            .map_err(JsonTreeMutateError::OutputBudget)
    }

    /// Runs mutable visitor callbacks without budget side effects.
    ///
    /// An explicit stack of borrowed child iterators visits each node before
    /// its children. The visitor may replace the current value or skip its
    /// descendants; its first error stops traversal and is returned unchanged.
    /// Object children follow the map backend's native iteration order.
    ///
    /// # Type Parameters
    ///
    /// * `V` - Visitor receiving each mutable value and its location context.
    ///
    /// # Parameters
    ///
    /// * `root` - Root value whose nodes are visited and may be replaced.
    /// * `visitor` - Callback applied before descending into each node's
    ///   children.
    ///
    /// # Returns
    ///
    /// `Ok(())` after all selected callbacks complete, or the first visitor
    /// error before traversal finishes.
    ///
    /// # Errors
    ///
    /// Returns the visitor's error unchanged when a callback fails; mutations
    /// already made to `root` remain in place.
    ///
    /// # Panics
    ///
    /// Panics if the depth of a materialized value cannot be represented as a
    /// `usize`. A visitor panic propagates unchanged; stack unwinding drops all
    /// borrowed cursors and leaves completed in-place mutations visible.
    fn mutate<V>(root: &mut Value, visitor: &mut V) -> Result<(), V::Error>
    where
        V: JsonTreeMutVisitor,
    {
        let control = visitor.visit(
            root,
            JsonTreeContext {
                depth: 1,
                location: JsonTreeLocation::Root,
            },
        )?;
        let mut stack = Vec::new();
        if control == JsonTreeControl::Descend
            && let Some(cursor) = MutChildCursor::new(root)
        {
            stack.push((cursor, 1usize));
        }
        while let Some((cursor, parent_depth)) = stack.last_mut() {
            let Some((child, location)) = cursor.next() else {
                stack.pop();
                continue;
            };
            let depth = parent_depth
                .checked_add(1)
                .expect("a materialized JSON tree cannot have usize::MAX nesting depth");
            let control = visitor.visit(child, JsonTreeContext { depth, location })?;
            if control == JsonTreeControl::Descend
                && let Some(cursor) = MutChildCursor::new(child)
            {
                stack.push((cursor, depth));
            }
        }
        Ok(())
    }
}