Skip to main content

dive_value/
depth.rs

1//! A nesting limit for the recursive algorithms.
2//!
3//! Dropping, `==`, [`Value::cmp_with`](crate::Value::cmp_with), hashing and
4//! fingerprinting are iterative and handle any nesting. TLC's checked operations
5//! ([`crate::tlc`]), printing and JSON recurse. They refuse values nested more than
6//! [`MAX_DEPTH`] levels deep with [`ErrorKind::DiveLimit`] rather than overflow the
7//! stack. TLC itself is limited only by the JVM stack (`-Xss`).
8
9use std::cell::Cell;
10
11use crate::error::{ErrorKind, Result, ValueError};
12
13/// The deepest nesting the recursive algorithms accept: safe on a 2 MiB thread stack
14/// even in debug builds (measured margin: about 1.5x).
15pub const MAX_DEPTH: u32 = 500;
16
17thread_local! {
18    static DEPTH: Cell<u32> = const { Cell::new(0) };
19}
20
21/// Current checked-operation nesting on this thread, without entering a level.
22/// This snapshot changes no depth policy and grants no authority to skip work.
23#[must_use]
24pub fn checked_operation_depth() -> u32 {
25    DEPTH.with(Cell::get)
26}
27
28/// One level of recursion; released on drop.
29pub(crate) struct Guard(());
30
31impl Guard {
32    /// Enters one level.
33    pub(crate) fn enter() -> Result<Self> {
34        let d = DEPTH.with(|d| {
35            let v = d.get() + 1;
36            d.set(v);
37            v
38        });
39        let guard = Self(());
40        if d > MAX_DEPTH {
41            return Err(too_deep());
42        }
43        Ok(guard)
44    }
45}
46
47impl Drop for Guard {
48    fn drop(&mut self) {
49        DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
50    }
51}
52
53pub(crate) fn too_deep() -> ValueError {
54    ValueError::new(
55        ErrorKind::DiveLimit,
56        format!(
57            "The value is nested more than {MAX_DEPTH} levels deep, more than dive's checked operations, printing and JSON support."
58        ),
59    )
60}