qubit_json/value/traverse/json_tree_visitor.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//! Defines callbacks for a read-only JSON tree traversal.
9
10use serde_json::Value;
11
12use super::JsonTreeContext;
13
14/// Receives enter and leave events for budget-admitted JSON tree nodes.
15///
16/// # Examples
17///
18/// ```
19/// use qubit_json::value::traverse::{
20/// JsonTreeContext, JsonTreeVisitor,
21/// };
22/// use serde_json::Value;
23///
24/// struct CountingVisitor {
25/// count: usize,
26/// }
27/// impl JsonTreeVisitor for CountingVisitor {
28/// type Error = std::convert::Infallible;
29///
30/// fn enter(
31/// &mut self,
32/// _: &Value,
33/// _: JsonTreeContext<'_>,
34/// ) -> Result<(), Self::Error> {
35/// self.count += 1;
36/// Ok(())
37/// }
38/// }
39///
40/// let _visitor = CountingVisitor { count: 0 };
41/// ```
42pub trait JsonTreeVisitor {
43 /// Domain-specific failure returned by this visitor.
44 type Error;
45
46 /// Handles a node after its budget admission and before its descendants.
47 ///
48 /// # Parameters
49 ///
50 /// * `value` - Admitted node being visited.
51 /// * `context` - Root-relative location and depth of the node.
52 ///
53 /// # Returns
54 ///
55 /// `Ok(())` to continue traversal, or the visitor's error to stop it.
56 fn enter(&mut self, value: &Value, context: JsonTreeContext<'_>) -> Result<(), Self::Error>;
57
58 /// Handles a node after all of its descendants have been handled.
59 ///
60 /// # Parameters
61 ///
62 /// * `value` - Admitted node whose descendants have been visited.
63 /// * `context` - Root-relative location and depth of the node.
64 ///
65 /// # Returns
66 ///
67 /// `Ok(())` to continue traversal, or the visitor's error to stop it.
68 fn leave(&mut self, _value: &Value, _context: JsonTreeContext<'_>) -> Result<(), Self::Error> {
69 Ok(())
70 }
71}