use std::cell::Cell;
use crate::error::{ErrorKind, Result, ValueError};
pub const MAX_DEPTH: u32 = 500;
thread_local! {
static DEPTH: Cell<u32> = const { Cell::new(0) };
}
#[must_use]
pub fn checked_operation_depth() -> u32 {
DEPTH.with(Cell::get)
}
pub(crate) struct Guard(());
impl Guard {
pub(crate) fn enter() -> Result<Self> {
let d = DEPTH.with(|d| {
let v = d.get() + 1;
d.set(v);
v
});
let guard = Self(());
if d > MAX_DEPTH {
return Err(too_deep());
}
Ok(guard)
}
}
impl Drop for Guard {
fn drop(&mut self) {
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
pub(crate) fn too_deep() -> ValueError {
ValueError::new(
ErrorKind::DiveLimit,
format!(
"The value is nested more than {MAX_DEPTH} levels deep, more than dive's checked operations, printing and JSON support."
),
)
}