use std::borrow::Cow;
use serde_json::Value;
use crate::types::{ArgValue, DslError, ParsedOp, NESTING_DEPTH_LIMIT};
pub(crate) fn scan_string_end(src: &[u8], start: usize) -> Result<usize, DslError> {
let mut i = start + 1;
while i < src.len() {
match src[i] as char {
'\\' => {
i += 2; continue;
}
'"' => return Ok(i + 1),
_ => i += 1,
}
}
Err(DslError::UnclosedString)
}
pub(crate) struct ControlByteHit {
pub(crate) normalized_pos: usize,
pub(crate) raw_pos: usize,
pub(crate) byte: u8,
pub(crate) preceded_by_backslash: bool,
}
pub(crate) struct NormalizedQuotedString<'a> {
pub(crate) text: Cow<'a, str>,
pub(crate) first_control_byte: Option<ControlByteHit>,
}
pub(crate) fn normalize_quoted_string(raw: &str) -> NormalizedQuotedString<'_> {
let mut out = None;
let mut first_control_byte = None;
let mut chars = raw.char_indices().peekable();
let mut hex_slots_remaining = 0u32;
let mut hex_acc = 0u32;
let mut hex_valid = true;
let mut after_high_surrogate = false;
while let Some((pos, c)) = chars.next() {
if hex_slots_remaining > 0 {
hex_slots_remaining -= 1;
match c.to_digit(16) {
Some(d) => hex_acc = (hex_acc << 4) | d,
None => hex_valid = false,
}
if (c as u32) < 0x20 && out.is_none() {
let mut owned = String::with_capacity(raw.len() + 8);
owned.push_str(&raw[..pos]);
out = Some(owned);
}
if let Some(out) = out.as_mut() {
out.push(c);
}
if hex_slots_remaining == 0 {
after_high_surrogate = hex_valid && (0xD800..=0xDBFF).contains(&hex_acc);
}
continue;
}
let prev_was_high_surrogate = after_high_surrogate;
after_high_surrogate = false;
if c == '\\' {
if let Some(out) = out.as_mut() {
out.push(c);
}
if let Some(&(next_pos, next_c)) = chars.peek() {
chars.next();
if next_c == 'u' {
if let Some(out) = out.as_mut() {
out.push(next_c);
}
hex_slots_remaining = 4;
hex_acc = 0;
hex_valid = true;
continue;
}
if (next_c as u32) < 0x20
&& !prev_was_high_surrogate
&& first_control_byte.is_none()
{
let out = out.get_or_insert_with(|| {
let mut owned = String::with_capacity(raw.len() + 8);
owned.push_str(&raw[..next_pos]);
owned
});
first_control_byte = Some(ControlByteHit {
normalized_pos: out.len(),
raw_pos: next_pos,
byte: next_c as u8,
preceded_by_backslash: true,
});
}
if (next_c as u32) < 0x20 && out.is_none() {
let mut owned = String::with_capacity(raw.len() + 8);
owned.push_str(&raw[..next_pos]);
out = Some(owned);
}
if let Some(out) = out.as_mut() {
out.push(next_c);
}
}
continue;
}
match c {
'\n' | '\r' | '\t' => {
let out = out.get_or_insert_with(|| {
let mut owned = String::with_capacity(raw.len() + 8);
owned.push_str(&raw[..pos]);
owned
});
match c {
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
_ => unreachable!(),
}
}
c if (c as u32) < 0x20 => {
let out = out.get_or_insert_with(|| {
let mut owned = String::with_capacity(raw.len() + 8);
owned.push_str(&raw[..pos]);
owned
});
if first_control_byte.is_none() {
first_control_byte = Some(ControlByteHit {
normalized_pos: out.len(),
raw_pos: pos,
byte: c as u8,
preceded_by_backslash: false,
});
}
out.push(c);
}
c => {
if let Some(out) = out.as_mut() {
out.push(c);
}
}
}
}
NormalizedQuotedString {
text: out.map_or(Cow::Borrowed(raw), Cow::Owned),
first_control_byte,
}
}
pub(crate) fn char_label(c: char) -> &'static str {
match c {
'(' => "'('",
')' => "')'",
'[' => "'['",
']' => "']'",
'=' => "'='",
',' => "','",
_ => "expected char",
}
}
pub(super) fn is_prev_ref_string(s: &str) -> bool {
s == "$prev" || s.starts_with("$prev.") || s.starts_with("$prev[")
}
pub(crate) fn json_value_contains_prev_ref(v: &Value) -> bool {
json_value_contains_prev_ref_at(v, 0)
}
fn json_value_contains_prev_ref_at(v: &Value, depth: usize) -> bool {
if depth > NESTING_DEPTH_LIMIT {
return true;
}
match v {
Value::String(s) => is_prev_ref_string(s),
Value::Array(arr) => arr
.iter()
.any(|e| json_value_contains_prev_ref_at(e, depth + 1)),
Value::Object(map) => map
.values()
.any(|e| json_value_contains_prev_ref_at(e, depth + 1)),
_ => false,
}
}
pub(crate) fn check_json_nesting_depth(input: &str) -> Result<(), DslError> {
let bytes = input.as_bytes();
let mut i = 0;
let mut depth: usize = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => {
i = scan_string_end(bytes, i)?;
continue;
}
b'[' | b'{' => {
depth += 1;
if depth > NESTING_DEPTH_LIMIT {
return Err(DslError::NestingTooDeep {
pos: i,
depth,
max: NESTING_DEPTH_LIMIT,
});
}
}
b']' | b'}' => {
depth = depth.saturating_sub(1);
}
_ => {}
}
i += 1;
}
Ok(())
}
pub(crate) fn find_prev_ref_pos(op: &ParsedOp) -> Option<usize> {
for av in op.args.values() {
if arg_value_has_prev_ref(av) {
return Some(0);
}
}
None
}
fn arg_value_has_prev_ref(av: &ArgValue) -> bool {
match av {
ArgValue::PrevRef { .. } => true,
ArgValue::Array(els) => els.iter().any(arg_value_has_prev_ref),
ArgValue::Object(pairs) => pairs.iter().any(|(_, v)| arg_value_has_prev_ref(v)),
ArgValue::Value(_) => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_control_bytes_retain_only_the_first_hit() {
let raw = "\u{0}".repeat(4096);
let normalized = normalize_quoted_string(&raw);
let hit = normalized
.first_control_byte
.expect("first control byte must be recorded");
assert_eq!(
hit.raw_pos, 0,
"must record the earliest hit, not a later one"
);
assert_eq!(hit.byte, 0);
}
#[test]
fn control_free_string_stays_borrowed_after_single_scan() {
let raw = r#""quoted key""#;
let normalized = normalize_quoted_string(raw);
assert!(matches!(normalized.text, Cow::Borrowed(_)));
assert!(normalized.first_control_byte.is_none());
}
}