bluejay_parser/ast/
depth_limiter.rs

1use crate::ast::ParseError;
2
3pub const DEFAULT_MAX_DEPTH: usize = 2000;
4
5/// A depth limiter is used to limit the depth of the AST. This is useful to prevent stack overflows.
6/// This intentionally does not implement `Clone` or `Copy` to prevent passing this down the call stack without bumping.
7pub struct DepthLimiter {
8    max_depth: usize,
9    current_depth: usize,
10}
11
12impl Default for DepthLimiter {
13    fn default() -> Self {
14        Self {
15            max_depth: DEFAULT_MAX_DEPTH,
16            current_depth: 0,
17        }
18    }
19}
20
21impl DepthLimiter {
22    pub fn new(max_depth: usize) -> Self {
23        Self {
24            max_depth,
25            current_depth: 0,
26        }
27    }
28
29    pub fn bump(&self) -> Result<Self, ParseError> {
30        if self.current_depth >= self.max_depth {
31            Err(ParseError::MaxDepthExceeded)
32        } else {
33            Ok(Self {
34                max_depth: self.max_depth,
35                current_depth: self.current_depth + 1,
36            })
37        }
38    }
39}