qubit_json/value/traverse/json_tree_mutator.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Implements non-recursive, budget-aware mutable JSON tree processing.
9//!
10//! # Mutable traversal safety
11//!
12//! Each stack entry owns an iterator whose lifetime borrows one container in
13//! the exclusively borrowed root. A yielded child borrow lasts for the tree
14//! lifetime, so its descendants can be borrowed while ancestor iterators stay
15//! suspended in the stack. Visitors may replace the current value; borrowed
16//! container iterators prevent structural changes to ancestors until traversal
17//! finishes. No raw pointers or erased lifetimes are needed.
18
19use qubit_budget::ResourceQuantity;
20use qubit_budget::json::JsonValueTransaction;
21use serde_json::Value;
22
23use super::JsonTreeContext;
24use super::JsonTreeControl;
25use super::JsonTreeLocation;
26use super::JsonTreeMutVisitor;
27use super::JsonTreeMutateError;
28use super::JsonTreeReader;
29use super::internal::MutChildCursor;
30
31/// Mutates a JSON tree between independent input and output transactions.
32///
33/// The complete original tree is admitted before the first visitor callback.
34/// After all callbacks succeed, the complete mutated tree is admitted against
35/// the output transaction. Visitor failures and panics can retain partial
36/// mutations, while output accounting does not begin until visitor success.
37///
38/// # Type Parameters
39///
40/// * `R` - Resource identity shared by the two transactions.
41/// * `Q` - Quantity representation shared by the two transactions.
42///
43/// # Examples
44///
45/// ```
46/// use qubit_budget::json::{JsonResource, JsonValueBudget, JsonValueLimits};
47/// use qubit_json::value::traverse::{
48/// JsonTreeContext, JsonTreeControl, JsonTreeMutVisitor, JsonTreeMutator,
49/// };
50/// use serde_json::Value;
51///
52/// struct Visitor;
53/// impl JsonTreeMutVisitor for Visitor {
54/// type Error = std::convert::Infallible;
55///
56/// fn visit(
57/// &mut self,
58/// _: &mut Value,
59/// _: JsonTreeContext<'_>,
60/// ) -> Result<JsonTreeControl, Self::Error> {
61/// Ok(JsonTreeControl::SkipSubtree)
62/// }
63/// }
64///
65/// let limits = JsonValueLimits::<JsonResource, usize>::default();
66/// let mut input_budget = JsonValueBudget::new(limits);
67/// let mut output_budget = JsonValueBudget::new(limits);
68/// let mut input = input_budget.transaction();
69/// let mut output = output_budget.transaction();
70/// let mut mutator = JsonTreeMutator::new(&mut input, &mut output);
71/// let mut value = Value::Null;
72/// assert!(mutator.process(&mut value, &mut Visitor).is_ok());
73/// ```
74pub struct JsonTreeMutator<'input_transaction, 'input_budget, 'output_transaction, 'output_budget, R, Q>
75where
76 Q: ResourceQuantity,
77{
78 /// Transaction receiving the complete original-tree charges.
79 input: &'input_transaction mut JsonValueTransaction<'input_budget, R, Q>,
80 /// Transaction receiving the complete mutated-tree charges.
81 output: &'output_transaction mut JsonValueTransaction<'output_budget, R, Q>,
82}
83
84impl<'input_transaction, 'input_budget, 'output_transaction, 'output_budget, R, Q>
85 JsonTreeMutator<'input_transaction, 'input_budget, 'output_transaction, 'output_budget, R, Q>
86where
87 R: Clone,
88 Q: ResourceQuantity,
89{
90 /// Creates a mutator borrowing independent input and output transactions.
91 ///
92 /// # Parameters
93 ///
94 /// * `input` - Transaction receiving charges for the complete original
95 /// tree.
96 /// * `output` - Transaction receiving charges for the complete mutated
97 /// tree.
98 ///
99 /// # Returns
100 ///
101 /// A mutator borrowing both transactions for its lifetime.
102 #[inline(always)]
103 #[must_use]
104 pub fn new(
105 input: &'input_transaction mut JsonValueTransaction<'input_budget, R, Q>,
106 output: &'output_transaction mut JsonValueTransaction<'output_budget, R, Q>,
107 ) -> Self {
108 Self { input, output }
109 }
110
111 /// Admits the original tree, mutates it, and admits the final tree.
112 ///
113 /// Both admissions and all visitor callbacks use explicit stacks rather
114 /// than Rust recursion. `SkipSubtree` affects callbacks only; final output
115 /// admission always covers every resulting descendant.
116 ///
117 /// Callbacks may visit descendants added by earlier callbacks. Output
118 /// `max_nodes` and `max_depth` are checked only against the complete final
119 /// tree; they do not limit callback count or intermediate expansion. A
120 /// visitor that adds descendants must bound its own expansion and ensure
121 /// traversal terminates. Returning [`JsonTreeControl::SkipSubtree`] skips
122 /// descent from the current node, but the final tree is still subject to
123 /// output admission. See the
124 /// [mutable tree traversal guidance](https://github.com/qubit-ltd/rs-json/blob/main/doc/user_guide.md#read-and-mutate-existing-trees).
125 ///
126 /// # Type Parameters
127 ///
128 /// * `V` - Visitor controlling mutations and descendant callbacks.
129 ///
130 /// # Parameters
131 ///
132 /// * `root` - Root JSON value to process and mutate.
133 /// * `visitor` - Visitor applied after complete input admission.
134 ///
135 /// # Returns
136 ///
137 /// `Ok(())` after both complete trees fit and every callback succeeds.
138 ///
139 /// # Errors
140 ///
141 /// Returns [`JsonTreeMutateError::InputBudget`] before mutation when the
142 /// original tree is rejected, [`JsonTreeMutateError::Visitor`] after a
143 /// callback failure, or [`JsonTreeMutateError::OutputBudget`] after a
144 /// complete mutation whose result is rejected. Visitor and output failures
145 /// retain mutations already made to `root`.
146 ///
147 /// # Panics
148 ///
149 /// Propagates a panic from the visitor. Advancing traversal depth panics
150 /// only if a materialized tree depth exceeds the range of `usize`.
151 pub fn process<V>(&mut self, root: &mut Value, visitor: &mut V) -> Result<(), JsonTreeMutateError<R, Q, V::Error>>
152 where
153 V: JsonTreeMutVisitor,
154 {
155 JsonTreeReader::new(&mut *self.input)
156 .account(root)
157 .map_err(JsonTreeMutateError::InputBudget)?;
158 Self::mutate(root, visitor).map_err(JsonTreeMutateError::Visitor)?;
159 JsonTreeReader::new(&mut *self.output)
160 .account(root)
161 .map_err(JsonTreeMutateError::OutputBudget)
162 }
163
164 /// Runs mutable visitor callbacks without budget side effects.
165 ///
166 /// An explicit stack of borrowed child iterators visits each node before
167 /// its children. The visitor may replace the current value or skip its
168 /// descendants; its first error stops traversal and is returned unchanged.
169 /// Object children follow the map backend's native iteration order.
170 ///
171 /// # Type Parameters
172 ///
173 /// * `V` - Visitor receiving each mutable value and its location context.
174 ///
175 /// # Parameters
176 ///
177 /// * `root` - Root value whose nodes are visited and may be replaced.
178 /// * `visitor` - Callback applied before descending into each node's
179 /// children.
180 ///
181 /// # Returns
182 ///
183 /// `Ok(())` after all selected callbacks complete, or the first visitor
184 /// error before traversal finishes.
185 ///
186 /// # Errors
187 ///
188 /// Returns the visitor's error unchanged when a callback fails; mutations
189 /// already made to `root` remain in place.
190 ///
191 /// # Panics
192 ///
193 /// Panics if the depth of a materialized value cannot be represented as a
194 /// `usize`. A visitor panic propagates unchanged; stack unwinding drops all
195 /// borrowed cursors and leaves completed in-place mutations visible.
196 fn mutate<V>(root: &mut Value, visitor: &mut V) -> Result<(), V::Error>
197 where
198 V: JsonTreeMutVisitor,
199 {
200 let control = visitor.visit(
201 root,
202 JsonTreeContext {
203 depth: 1,
204 location: JsonTreeLocation::Root,
205 },
206 )?;
207 let mut stack = Vec::new();
208 if control == JsonTreeControl::Descend
209 && let Some(cursor) = MutChildCursor::new(root)
210 {
211 stack.push((cursor, 1usize));
212 }
213 while let Some((cursor, parent_depth)) = stack.last_mut() {
214 let Some((child, location)) = cursor.next() else {
215 stack.pop();
216 continue;
217 };
218 let depth = parent_depth
219 .checked_add(1)
220 .expect("a materialized JSON tree cannot have usize::MAX nesting depth");
221 let control = visitor.visit(child, JsonTreeContext { depth, location })?;
222 if control == JsonTreeControl::Descend
223 && let Some(cursor) = MutChildCursor::new(child)
224 {
225 stack.push((cursor, depth));
226 }
227 }
228 Ok(())
229 }
230}