pub fn check_toml_nesting_depth(
content: &str,
max_depth: usize,
) -> Result<(), usize>Expand description
Scans raw TOML text for table/array recursion deeper than max_depth.
toml-span::parse has no public option to cap recursion, so callers must
reject pathological input before handing it to the parser. This performs a
single-pass structural scan — no actual parsing, so it cannot itself
recurse or overflow — that bounds the two independent ways TOML content
drives toml-span’s table/array recursion:
- Bracket nesting:
[/{and]/}pairs, as in[[[1]]]or{a={a=1}}. - Dotted-key/header segments: each
.in a dotted key (a.b.c = 1) or dotted table header ([a.b.c]) creates one level of table nesting with zero bracket characters, so bracket-only counting alone is not sufficient. Dots are only counted in key position (start of a top-level statement, inside a[...]/[[...]]header, or right after{/,while the innermost open bracket is{) — never in value position, soa = 3.14and multi-segment version/date values are not miscounted.
Both counts accumulate into one shared depth budget bounded by
max_depth, since both are ways toml-span recurses. Bracket characters
and dots inside string literals or line comments are skipped, so this
does not misfire on values like "flask[async]>=3.0" or # example: [1, 2]. Both single-line ("...", '...', honoring \" escapes) and
multi-line ("""...""", '''...''', including a body that legally ends
with 1-2 extra literal quote characters before the closing delimiter, per
the TOML spec) string forms are recognized, so brackets and dots inside a
multi-line string body are never miscounted.
§Errors
Returns Err(depth) with the depth reached the instant nesting exceeds
max_depth.
§Examples
use deps_core::parser::check_toml_nesting_depth;
assert!(check_toml_nesting_depth(r#"a = [1, 2, [3, 4]]"#, 4).is_ok());
assert!(check_toml_nesting_depth("a = '''don't'''\nb = [1]", 4).is_ok());
assert!(check_toml_nesting_depth("a = 3.14\nb.c = 1", 4).is_ok());
let deeply_nested = format!("a = {}1{}", "[".repeat(10), "]".repeat(10));
assert_eq!(check_toml_nesting_depth(&deeply_nested, 4), Err(5));
let deep_dotted_key = format!("a{} = 1", ".a".repeat(10));
assert_eq!(check_toml_nesting_depth(&deep_dotted_key, 4), Err(5));