Skip to main content

unityrs_core/limits/
traversal.rs

1//! Charges shared by mutable-tree walks, parsers and language-boundary staging.
2use super::{Charge, ChargeError, Meter};
3use crate::{LimitError, LimitKind};
4use std::sync::Arc;
5
6/// A bounded tree operation. Its staging stays charged until handoff or refusal.
7pub struct TreeTraversal {
8    charge: Charge,
9    depth_limit: u32,
10}
11
12const _: () = crate::send_sync::<TreeTraversal>();
13
14impl TreeTraversal {
15    /// Use the input's existing memory and cumulative work account.
16    #[must_use]
17    pub fn new(meter: &Arc<Meter>, depth_limit: u32) -> Self {
18        Self {
19            charge: Charge::zero(meter),
20            depth_limit,
21        }
22    }
23
24    /// Check depth, then charge work and staging before an expansion.
25    /// Core-owned buffers additionally carry their own `MeteredVec` charges.
26    pub fn step(&mut self, depth: u64, memory: u64, work: u64) -> Result<(), ChargeError> {
27        if depth > u64::from(self.depth_limit) {
28            return Err(
29                LimitError::refused(LimitKind::TreeDepth, depth, self.depth_limit.into()).into(),
30            );
31        }
32        self.charge.meter().count_decode(work)?;
33        if memory > 0 {
34            self.charge.grow(memory)?;
35        }
36        Ok(())
37    }
38}