#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
use std::borrow::Cow;
use std::str::FromStr;
use memchr::{memchr, memchr2};
use thiserror::Error;
pub const MAX_DOTTED_PARTS: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Path {
reading: Reading,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Reading {
Steps(Vec<Step>),
WholeKeyFirst(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Step {
Key(String),
Index(usize),
Either(String, usize),
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PathError {
#[error("a path needs at least one key")]
Empty,
#[error("{why} at byte {at}")]
Syntax {
at: usize,
why: &'static str,
},
#[error("{parts} dotted parts, past the {max} a whole-key-first path takes", max = MAX_DOTTED_PARTS)]
TooManyParts {
parts: usize,
},
}
impl Path {
pub fn parse(text: &str) -> Result<Self, PathError> {
if text.is_empty() {
return Err(PathError::Empty);
}
let bytes = text.as_bytes();
let mut keys = Vec::new();
let mut at = 0;
let mut after_dot = false;
loop {
if bytes.get(at) == Some(&b'[') && !after_dot {
let (step, next) = if bytes.get(at + 1).is_some_and(u8::is_ascii_digit) {
bracketed_index(bytes, at)?
} else {
let (key, next) = quoted(bytes, at)?;
(Step::Key(key), next)
};
keys.push(step);
at = next;
} else {
let len = bytes[at..]
.iter()
.position(|&b| b == b'.' || b == b'[')
.unwrap_or(bytes.len() - at);
if len == 0 {
return Err(syntax(at, "a key name"));
}
keys.push(Step::Key(text[at..at + len].to_owned()));
at += len;
}
after_dot = false;
match bytes.get(at) {
None => return Ok(Self::steps(keys)),
Some(b'.') => {
at += 1;
after_dot = true;
}
Some(b'[') => {}
Some(_) => return Err(syntax(at, "`.` or `[` after `]`")),
}
}
}
pub fn from_keys<I, K>(keys: I) -> Result<Self, PathError>
where
I: IntoIterator<Item = K>,
K: Into<String>,
{
let keys: Vec<Step> = keys.into_iter().map(|k| Step::Key(k.into())).collect();
if keys.is_empty() {
return Err(PathError::Empty);
}
Ok(Self::steps(keys))
}
pub fn from_pointer(text: &str) -> Result<Self, PathError> {
let Some(rest) = text.strip_prefix('/') else {
return Err(if text.is_empty() {
PathError::Empty
} else {
syntax(0, "`/` to start a pointer")
});
};
let mut at = 1;
let mut steps = Vec::new();
for segment in rest.split('/') {
let mut key = String::with_capacity(segment.len());
let mut chars = segment.char_indices();
while let Some((i, c)) = chars.next() {
if c == '~' {
match chars.next() {
Some((_, '0')) => key.push('~'),
Some((_, '1')) => key.push('/'),
_ => return Err(syntax(at + i, "`~0` or `~1`")),
}
} else {
key.push(c);
}
}
at += segment.len() + 1;
let is_index = !key.is_empty()
&& key.bytes().all(|b| b.is_ascii_digit())
&& (key == "0" || !key.starts_with('0'));
let index = if is_index {
key.parse::<usize>().ok()
} else {
None
};
steps.push(match index {
Some(i) => Step::Either(key, i),
None => Step::Key(key),
});
}
Ok(Self::steps(steps))
}
pub fn whole_key_first(text: &str) -> Result<Self, PathError> {
let parts = text.split('.').count();
if parts > MAX_DOTTED_PARTS {
return Err(PathError::TooManyParts { parts });
}
Ok(Self {
reading: Reading::WholeKeyFirst(text.to_owned()),
})
}
pub(crate) const fn steps(steps: Vec<Step>) -> Self {
Self {
reading: Reading::Steps(steps),
}
}
#[cfg(feature = "json-paths")]
pub(crate) fn readings(&self) -> (Vec<Vec<Step>>, usize) {
match &self.reading {
Reading::Steps(steps) => (vec![steps.clone()], 0),
Reading::WholeKeyFirst(text) => {
let parts: Vec<&str> = text.split('.').collect();
let readings: Vec<Vec<Step>> = groupings(&parts)
.into_iter()
.map(|keys| keys.into_iter().map(Step::Key).collect())
.collect();
let plain = readings
.iter()
.position(|keys| keys.len() == parts.len())
.unwrap_or(0);
(readings, plain)
}
}
}
}
fn bracketed_index(bytes: &[u8], at: usize) -> Result<(Step, usize), PathError> {
let digits = bytes[at + 1..]
.iter()
.take_while(|b| b.is_ascii_digit())
.count();
let text = &bytes[at + 1..at + 1 + digits];
if text.len() > 1 && text[0] == b'0' {
return Err(syntax(at + 1, "an index with no leading zero"));
}
let index = std::str::from_utf8(text)
.ok()
.and_then(|t| t.parse::<usize>().ok())
.ok_or_else(|| syntax(at + 1, "an index that fits a usize"))?;
if bytes.get(at + 1 + digits) != Some(&b']') {
return Err(syntax(at + 1 + digits, "`]` after the index"));
}
Ok((Step::Index(index), at + 2 + digits))
}
impl FromStr for Path {
type Err = PathError;
fn from_str(text: &str) -> Result<Self, PathError> {
Self::parse(text)
}
}
const fn syntax(at: usize, why: &'static str) -> PathError {
PathError::Syntax { at, why }
}
fn quoted(bytes: &[u8], at: usize) -> Result<(String, usize), PathError> {
if bytes.get(at + 1) != Some(&b'"') {
return Err(syntax(at + 1, "a JSON string after `[`"));
}
let (end, _) = string_end(bytes, at + 2).map_err(|_| syntax(at + 1, "a closing quote"))?;
let mut key = Vec::new();
unescape(&bytes[at + 2..end], |part| key.extend_from_slice(part))
.map_err(|_| syntax(at + 1, "a JSON string"))?;
let key = String::from_utf8(key).map_err(|_| syntax(at + 1, "a JSON string"))?;
if bytes.get(end + 1) != Some(&b']') {
return Err(syntax(end + 1, "`]` after the key"));
}
Ok((key, end + 2))
}
#[cfg(feature = "json-paths")]
fn groupings(parts: &[&str]) -> Vec<Vec<String>> {
let mut out = vec![vec![parts.join(".")]];
for cut in 1..parts.len() {
let head = parts[..cut].join(".");
for rest in groupings(&parts[cut..]) {
let mut keys = Vec::with_capacity(rest.len() + 1);
keys.push(head.clone());
keys.extend(rest);
out.push(keys);
}
}
out
}
#[cfg(feature = "parse")]
#[inline]
pub(crate) fn needs_quotes(key: &str) -> bool {
key.bytes().any(|b| matches!(b, b'.' | b'[' | b']' | b'"'))
}
#[cfg(any(
feature = "parse-ndjson",
feature = "parse-xml",
feature = "parse-kv",
feature = "parse-csv",
feature = "parse-cef",
feature = "parse-leef",
feature = "parse-w3c",
feature = "parse-syslog",
))]
pub(crate) fn key_part(key: Cow<'_, str>) -> Cow<'_, str> {
if needs_quotes(&key) {
let mut part = String::with_capacity(key.len() + 4);
push_quoted(&mut part, &key);
Cow::Owned(part)
} else {
key
}
}
#[cfg(feature = "parse")]
pub(crate) fn push_key(name: &mut String, key: &str) {
if needs_quotes(key) {
push_quoted(name, key);
} else {
if !name.is_empty() {
name.push('.');
}
name.push_str(key);
}
}
#[cfg(feature = "parse")]
fn push_quoted(out: &mut String, key: &str) {
out.push_str("[\"");
for c in key.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if u32::from(c) < 0x20 => {
out.push_str("\\u00");
let code = u32::from(c);
for digit in [code >> 4, code & 0xF] {
out.push(char::from_digit(digit, 16).unwrap_or('0'));
}
}
c => out.push(c),
}
}
out.push_str("\"]");
}
#[cfg(feature = "parse")]
pub(crate) fn canonical(name: &str) -> Cow<'_, str> {
if !name.contains("[\"") {
return Cow::Borrowed(name);
}
let mut out = String::with_capacity(name.len());
for key in keys(name) {
push_key(&mut out, &key);
}
Cow::Owned(out)
}
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
fn quoted_part(text: &str) -> Option<(String, usize)> {
if !text.starts_with("[\"") {
return None;
}
let (key, end) = quoted(text.as_bytes(), 0).ok()?;
matches!(text.as_bytes().get(end), None | Some(b'.' | b'[')).then_some((key, end))
}
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
pub(crate) fn first_key(name: &str) -> (Cow<'_, str>, &str) {
if let Some((key, end)) = quoted_part(name) {
return (Cow::Owned(key), &name[end..]);
}
let bytes = name.as_bytes();
let mut at = usize::from(name.starts_with('['));
let end = loop {
let Some(i) = bytes.get(at..).and_then(|rest| memchr2(b'.', b'[', rest)) else {
break bytes.len();
};
let j = at + i;
if bytes[j] == b'.' || quoted_part(&name[j..]).is_some() {
break j;
}
at = j + 1;
};
(Cow::Borrowed(&name[..end]), &name[end..])
}
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
pub(crate) fn after_key(rest: &str) -> Option<&str> {
if rest.is_empty() {
None
} else {
Some(rest.strip_prefix('.').unwrap_or(rest))
}
}
#[cfg(feature = "parse")]
pub(crate) fn below(rest: &str) -> Option<&str> {
rest.strip_prefix('.')
.or_else(|| quoted_part(rest).map(|_| rest))
}
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
pub(crate) fn keys(name: &str) -> impl Iterator<Item = Cow<'_, str>> {
let mut rest = Some(name);
std::iter::from_fn(move || {
let (key, after) = first_key(rest?);
rest = after_key(after);
Some(key)
})
}
#[derive(Debug)]
pub(crate) struct Malformed;
#[inline]
pub(crate) fn string_end(json: &[u8], from: usize) -> Result<(usize, bool), Malformed> {
let mut at = from;
let mut escaped = false;
loop {
let rest = json.get(at..).ok_or(Malformed)?;
let i = memchr2(b'"', b'\\', rest).ok_or(Malformed)?;
if rest[i] == b'"' {
return Ok((at + i, escaped));
}
escaped = true;
at += i + 2;
}
}
pub(crate) fn unescape(mut raw: &[u8], mut out: impl FnMut(&[u8])) -> Result<(), Malformed> {
loop {
let run = memchr(b'\\', raw).unwrap_or(raw.len());
let (text, rest) = raw.split_at(run);
if text.iter().any(|&b| b < 0x20) {
return Err(Malformed);
}
out(text);
let Some((_, rest)) = rest.split_first() else {
return Ok(());
};
let (&escape, rest) = rest.split_first().ok_or(Malformed)?;
raw = rest;
let byte = match escape {
b'"' => b'"',
b'\\' => b'\\',
b'/' => b'/',
b'b' => 0x08,
b'f' => 0x0c,
b'n' => b'\n',
b'r' => b'\r',
b't' => b'\t',
b'u' => {
let (c, rest) = code_point(raw)?;
raw = rest;
out(c.encode_utf8(&mut [0; 4]).as_bytes());
continue;
}
_ => return Err(Malformed),
};
out(&[byte]);
}
}
fn code_point(raw: &[u8]) -> Result<(char, &[u8]), Malformed> {
let high = hex4(raw)?;
let mut rest = &raw[4..];
let code = match high {
0xD800..=0xDBFF => {
let low = hex4(rest.strip_prefix(b"\\u").ok_or(Malformed)?)?;
if !(0xDC00..=0xDFFF).contains(&low) {
return Err(Malformed);
}
rest = &rest[6..];
0x1_0000 + ((high - 0xD800) << 10) + (low - 0xDC00)
}
0xDC00..=0xDFFF => return Err(Malformed),
code => code,
};
Ok((char::from_u32(code).ok_or(Malformed)?, rest))
}
fn hex4(raw: &[u8]) -> Result<u32, Malformed> {
raw.get(..4)
.ok_or(Malformed)?
.iter()
.try_fold(0, |code, &b| {
let digit = char::from(b).to_digit(16).ok_or(Malformed)?;
Ok((code << 4) | digit)
})
}
#[cfg(all(test, feature = "parse"))]
mod tests;