Skip to main content

check_json_nesting_depth

Function check_json_nesting_depth 

Source
pub fn check_json_nesting_depth(
    content: &[u8],
    max_depth: usize,
) -> Result<(), usize>
Expand description

Scans raw JSON bytes for [/{ nesting deeper than max_depth, before handing the bytes to serde_json::from_slice/from_str.

A single-pass structural scan — no actual parsing, so it cannot itself recurse or overflow. String contents (JSON’s only escaping construct) are tracked so bracket characters inside string literals are never miscounted as structural nesting. Multi-byte UTF-8 sequences are safe to scan byte-by-byte here: none of their continuation bytes collide with the ASCII structural characters this function looks for.

An unterminated (or truncated) string literal makes the scanner treat the rest of the buffer as string content and return Ok, undercounting any nesting that follows. This is safe: serde_json tokenizes the same bytes and will independently reject the identical malformed/truncated string (an EOF-while-parsing-string or similar syntax error) before its own recursive descent could ever reach nesting beyond what this scanner already counted up to the unterminated quote.

§Errors

Returns Err(depth) with the depth reached the instant nesting exceeds max_depth.

§Examples

use deps_core::parser::check_json_nesting_depth;

assert!(check_json_nesting_depth(br#"{"a":[1,2,{"b":3}]}"#, 4).is_ok());

let deeply_nested = format!("{}1{}", "[".repeat(10), "]".repeat(10));
assert_eq!(check_json_nesting_depth(deeply_nested.as_bytes(), 4), Err(5));