use serde_json::Value;
use crate::error::ValidationError;
pub const MAX_JSON_NODES: usize = 1_000_000;
pub const MAX_JSON_DEPTH: usize = 128;
pub fn check_json_budget(input: &[u8]) -> Result<(), ValidationError> {
let mut nodes = 0usize;
let mut depth = 0usize;
let mut in_string = false;
let mut escaped = false;
let mut in_token = false;
for byte in input {
if in_string {
if escaped {
escaped = false;
} else if *byte == b'\\' {
escaped = true;
} else if *byte == b'"' {
in_string = false;
}
continue;
}
match *byte {
b'"' => {
nodes += 1;
in_string = true;
in_token = false;
}
b'{' | b'[' => {
nodes += 1;
depth += 1;
in_token = false;
}
b'}' | b']' => {
depth = depth.saturating_sub(1);
in_token = false;
}
b',' | b':' | b' ' | b'\t' | b'\r' | b'\n' => in_token = false,
_ => {
if !in_token {
nodes += 1;
}
in_token = true;
}
}
if nodes > MAX_JSON_NODES || depth > MAX_JSON_DEPTH {
return Err(ValidationError::JsonBudget);
}
}
Ok(())
}
pub fn require_string(
value: Option<&Value>,
name: &'static str,
max_bytes: usize,
) -> Result<String, ValidationError> {
match value {
Some(Value::String(text)) if !text.is_empty() && text.len() <= max_bytes => {
Ok(text.clone())
}
_ => Err(ValidationError::PayloadString { name, max_bytes }),
}
}
pub fn require_integer(
value: Option<&Value>,
name: &'static str,
min: u64,
max: u64,
) -> Result<u64, ValidationError> {
let number = value
.and_then(Value::as_f64)
.filter(|number| number.is_finite() && number.fract() == 0.0)
.ok_or(ValidationError::PayloadInteger { name, min, max })?;
if number < min as f64 || number > max as f64 {
return Err(ValidationError::PayloadInteger { name, min, max });
}
Ok(number as u64)
}