Skip to main content

d2_rs_math/
input_limits.rs

1// SPDX-License-Identifier: MPL-2.0
2//! d2renderers/d2latex/limits.go. Validate before recursive MathJax parsing.
3use crate::MathError;
4
5/// Maximum UTF-8 byte length admitted by D2's LaTeX renderer.
6pub const MAX_INPUT_BYTES: usize = 4 << 10;
7/// Maximum unescaped, uncommented brace-group nesting.
8pub const MAX_GROUP_NESTING_DEPTH: usize = 128;
9
10/// D2's shared LaTeX admission policy. Rust strings already guarantee UTF-8.
11pub fn validate_input(input: &str) -> Result<(), MathError> {
12    if input.len() > MAX_INPUT_BYTES {
13        return Err(MathError::InputLimit(format!(
14            "latex input is {} bytes, exceeding limit {MAX_INPUT_BYTES}",
15            input.len()
16        )));
17    }
18    let (mut depth, mut backslashes, mut in_comment) = (0usize, 0usize, false);
19    for &c in input.as_bytes() {
20        if in_comment {
21            if c == b'\n' || c == b'\r' {
22                in_comment = false;
23            }
24            continue;
25        }
26        if c == b'\\' {
27            backslashes += 1;
28            continue;
29        }
30        let escaped = backslashes % 2 != 0;
31        backslashes = 0;
32        if escaped {
33            continue;
34        }
35        match c {
36            b'%' => in_comment = true,
37            b'{' => {
38                depth += 1;
39                if depth > MAX_GROUP_NESTING_DEPTH {
40                    return Err(MathError::InputLimit(format!(
41                        "latex group nesting depth {depth} exceeds limit {MAX_GROUP_NESTING_DEPTH}"
42                    )));
43                }
44            }
45            b'}' => depth = depth.saturating_sub(1),
46            _ => {}
47        }
48    }
49    Ok(())
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    #[test]
56    fn byte_and_group_limits_precede_parsing() {
57        assert!(validate_input(&"x".repeat(MAX_INPUT_BYTES)).is_ok());
58        assert_eq!(
59            validate_input(&"x".repeat(MAX_INPUT_BYTES + 1))
60                .unwrap_err()
61                .to_string(),
62            "latex input is 4097 bytes, exceeding limit 4096"
63        );
64        let nested = format!("{}x{}", "{".repeat(128), "}".repeat(128));
65        assert!(validate_input(&nested).is_ok());
66        let too_deep = format!("{{{nested}}}");
67        for check in [crate::render, crate::render_exact] {
68            assert_eq!(
69                check(&too_deep).unwrap_err().to_string(),
70                "latex group nesting depth 129 exceeds limit 128"
71            );
72        }
73        assert_eq!(
74            crate::measure(&too_deep).unwrap_err().to_string(),
75            "latex group nesting depth 129 exceeds limit 128"
76        );
77        assert!(
78            validate_input(&"é".repeat(2049))
79                .unwrap_err()
80                .to_string()
81                .contains("4098 bytes")
82        );
83    }
84    #[test]
85    fn escape_parity_comments_and_unmatched_closes_follow_source() {
86        assert!(validate_input(&r"\{".repeat(129)).is_ok());
87        assert!(
88            validate_input(&format!(
89                "{}%{}\r{}",
90                "{".repeat(128),
91                "{".repeat(129),
92                "}".repeat(128)
93            ))
94            .is_ok()
95        );
96        assert!(validate_input(&format!("{}\\%{{", "{".repeat(128))).is_err());
97        assert!(
98            validate_input(&format!("{}\\\\%{{\n{}", "{".repeat(128), "}".repeat(128))).is_ok()
99        );
100        assert!(validate_input(&format!("}}}}{}", "{".repeat(128))).is_ok());
101    }
102}