use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use memchr::memchr;
use super::{BLOCK, Classes, ODD_BITS, prefix_xor};
pub(super) use crate::path::{Malformed, string_end, unescape};
use crate::path::{Path, Step};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Holder {
Object,
Array,
Either,
}
impl Holder {
const fn of(step: &Step) -> Self {
match step {
Step::Key(_) => Self::Object,
Step::Index(_) => Self::Array,
Step::Either(..) => Self::Either,
}
}
const fn holds(self, kind: Kind) -> bool {
matches!(
(self, kind),
(Self::Object | Self::Either, Kind::Object) | (Self::Array | Self::Either, Kind::Array)
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
Object,
Array,
String,
Number,
Bool,
Null,
}
impl Kind {
pub(super) const fn of(byte: u8) -> Option<Self> {
match byte {
b'{' => Some(Self::Object),
b'[' => Some(Self::Array),
b'"' => Some(Self::String),
b't' | b'f' => Some(Self::Bool),
b'n' => Some(Self::Null),
b'-' | b'0'..=b'9' => Some(Self::Number),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Raw<'a> {
text: &'a str,
kind: Kind,
start: usize,
}
impl<'a> Raw<'a> {
pub(super) const fn new(text: &'a str, kind: Kind, start: usize) -> Self {
Self { text, kind, start }
}
#[must_use]
pub const fn span(self) -> Range<usize> {
self.start..self.start + self.text.len()
}
#[must_use]
pub const fn text(self) -> &'a str {
self.text
}
#[must_use]
pub const fn kind(self) -> Kind {
self.kind
}
#[must_use]
pub fn to_str(self) -> Option<Cow<'a, str>> {
if self.kind != Kind::String {
return None;
}
let inner = self.text.strip_prefix('"')?.strip_suffix('"')?;
if memchr(b'\\', inner.as_bytes()).is_none() {
return Some(Cow::Borrowed(inner));
}
let mut out = Vec::with_capacity(inner.len());
unescape(inner.as_bytes(), |part| out.extend_from_slice(part)).ok()?;
String::from_utf8(out).ok().map(Cow::Owned)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Slot<'a> {
Found(Raw<'a>),
MissingKey,
MissingParent(usize),
WrongParentType(usize),
Malformed,
}
impl<'a> Slot<'a> {
#[must_use]
pub const fn found(self) -> Option<Raw<'a>> {
match self {
Self::Found(raw) => Some(raw),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Paths {
nodes: Vec<Node>,
edges: Vec<Edge>,
items: Vec<(usize, usize)>,
slots: Vec<Plan>,
longest: usize,
}
#[derive(Debug, Clone, Copy)]
struct Node {
first: usize,
count: usize,
items_first: usize,
items_count: usize,
wanted: bool,
}
#[derive(Debug, Clone)]
struct Edge {
key: Box<str>,
node: usize,
control: bool,
}
#[derive(Debug, Clone)]
struct Plan {
readings: Box<[Box<[(usize, Holder)]>]>,
plain: usize,
}
impl Paths {
#[must_use]
pub fn new<I: IntoIterator<Item = Path>>(paths: I) -> Self {
let mut tree = Tree::default();
let slots = paths
.into_iter()
.map(|path| {
let (readings, plain) = path.readings();
Plan {
readings: readings.into_iter().map(|keys| tree.insert(keys)).collect(),
plain,
}
})
.collect();
tree.finish(slots)
}
#[must_use]
pub const fn len(&self) -> usize {
self.slots.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.slots.is_empty()
}
pub fn read<'s, 'a>(&'s self, json: &'a [u8], slots: &'s mut Slots) -> Values<'s, 'a> {
let Slots { visits, key } = slots;
visits.clear();
visits.resize(self.nodes.len(), Visit::default());
if !self.slots.is_empty() {
Walk {
paths: self,
json,
at: 0,
visits: visits.as_mut_slice(),
key,
}
.record();
}
Values {
paths: self,
visits: visits.as_slice(),
json,
}
}
}
struct Tree {
children: Vec<Vec<(String, usize)>>,
items: Vec<Vec<(usize, usize)>>,
wanted: Vec<bool>,
index: HashMap<(usize, Child), usize>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Child {
Key(String),
Index(usize),
}
impl Default for Tree {
fn default() -> Self {
Self {
children: vec![Vec::new()],
items: vec![Vec::new()],
wanted: vec![false],
index: HashMap::new(),
}
}
}
impl Tree {
fn insert(&mut self, steps: Vec<Step>) -> Box<[(usize, Holder)]> {
let mut at = 0;
let mut chain = Vec::with_capacity(steps.len());
for step in steps {
let holder = Holder::of(&step);
let (child, index) = match step {
Step::Key(key) => (Child::Key(key), None),
Step::Index(i) => (Child::Index(i), None),
Step::Either(key, i) => (Child::Key(key), Some(i)),
};
let node = self.node(at, child);
if let Some(i) = index
&& !self.items[at].contains(&(i, node))
{
self.items[at].push((i, node));
}
chain.push((node, holder));
at = node;
}
self.wanted[at] = true;
chain.into_boxed_slice()
}
fn node(&mut self, at: usize, child: Child) -> usize {
let next = self.children.len();
let node = *self.index.entry((at, child.clone())).or_insert(next);
if node == next {
self.children.push(Vec::new());
self.items.push(Vec::new());
self.wanted.push(false);
match child {
Child::Key(key) => self.children[at].push((key, node)),
Child::Index(i) => self.items[at].push((i, node)),
}
}
node
}
fn finish(self, slots: Vec<Plan>) -> Paths {
let mut nodes = Vec::with_capacity(self.children.len());
let mut edges = Vec::new();
let mut all_items = Vec::new();
let mut longest = 0;
for ((mut children, mut items), wanted) in
self.children.into_iter().zip(self.items).zip(self.wanted)
{
children.sort_unstable_by(|(a, _), (b, _)| by_length(a.as_bytes(), b.as_bytes()));
items.sort_unstable();
nodes.push(Node {
first: edges.len(),
count: children.len(),
items_first: all_items.len(),
items_count: items.len(),
wanted,
});
all_items.extend(items);
for (key, node) in children {
longest = longest.max(key.len());
edges.push(Edge {
control: key.bytes().any(|b| b < 0x20),
key: key.into_boxed_str(),
node,
});
}
}
Paths {
nodes,
edges,
items: all_items,
slots,
longest,
}
}
}
fn by_length(a: &[u8], b: &[u8]) -> std::cmp::Ordering {
a.len().cmp(&b.len()).then_with(|| a.cmp(b))
}
#[derive(Debug, Clone, Default)]
pub struct Slots {
visits: Vec<Visit>,
key: Vec<u8>,
}
impl Slots {
#[must_use]
pub const fn new() -> Self {
Self {
visits: Vec::new(),
key: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
struct Visit {
start: usize,
end: usize,
kind: Option<Kind>,
closed: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct Values<'s, 'a> {
paths: &'s Paths,
visits: &'s [Visit],
json: &'a [u8],
}
impl<'a> Values<'_, 'a> {
#[must_use]
pub fn get(&self, i: usize) -> Option<Slot<'a>> {
self.paths.slots.get(i).map(|plan| self.slot(plan))
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Slot<'a>> {
self.paths.slots.iter().map(|plan| self.slot(plan))
}
#[must_use]
pub const fn len(&self) -> usize {
self.paths.slots.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.paths.slots.is_empty()
}
fn slot(&self, plan: &Plan) -> Slot<'a> {
let mut miss = Slot::Malformed;
for (i, chain) in plan.readings.iter().enumerate() {
match self.reading(chain) {
Slot::Malformed => return Slot::Malformed,
found @ Slot::Found(_) => return found,
other if i == plan.plain => miss = other,
_ => {}
}
}
miss
}
fn reading(&self, chain: &[(usize, Holder)]) -> Slot<'a> {
let json = self.json;
let mut parent = self.visits[0];
for (i, &(node, holder)) in chain.iter().enumerate() {
match parent.kind {
Some(kind) if holder.holds(kind) => {}
Some(_) => return Slot::WrongParentType(i),
None => return Slot::Malformed,
}
let visit = self.visits[node];
let last = i + 1 == chain.len();
let Some(kind) = visit.kind else {
return match (parent.closed, last) {
(false, _) => Slot::Malformed,
(true, true) => Slot::MissingKey,
(true, false) => Slot::MissingParent(i),
};
};
if last {
if visit.end == 0 {
return Slot::Malformed;
}
return checked(kind, &json[visit.start..visit.end])
.map_or(Slot::Malformed, |text| {
Slot::Found(Raw::new(text, kind, visit.start))
});
}
parent = visit;
}
Slot::Malformed
}
}
pub(super) fn checked(kind: Kind, text: &[u8]) -> Option<&str> {
let well_formed = match kind {
Kind::Object | Kind::Array => true,
Kind::String => text
.strip_prefix(b"\"")
.and_then(|t| t.strip_suffix(b"\""))
.is_some_and(|inner| unescape(inner, |_| {}).is_ok()),
Kind::Number => number(text),
Kind::Bool => text == b"true" || text == b"false",
Kind::Null => text == b"null",
};
if well_formed {
std::str::from_utf8(text).ok()
} else {
None
}
}
#[cfg(feature = "json-keys")]
pub(super) fn valid(json: &[u8], from: usize, to: usize, depth: usize) -> Result<(), usize> {
let json = &json[..to];
let space = |mut at: usize| {
while matches!(json.get(at), Some(b' ' | b'\t' | b'\n' | b'\r')) {
at += 1;
}
at
};
let mut open: u128 = 0;
let mut n = 0;
let mut at = from;
loop {
at = space(at);
match json.get(at) {
Some(b'"') => at = valid_string(json, at)?,
Some(&b @ (b'{' | b'[')) => {
if n >= depth.min(128) {
return Err(at);
}
let object = b == b'{';
open = (open << 1) | u128::from(object);
n += 1;
at = space(at + 1);
let empty = json.get(at) == Some(if object { &b'}' } else { &b']' });
if !empty {
if object {
at = valid_key(json, at, space)?;
}
continue;
}
at += 1;
open >>= 1;
n -= 1;
}
Some(b't') if json[at..].starts_with(b"true") => at += 4,
Some(b'f') if json[at..].starts_with(b"false") => at += 5,
Some(b'n') if json[at..].starts_with(b"null") => at += 4,
Some(b'-' | b'0'..=b'9') => {
let len = json[at..]
.iter()
.position(|&b| {
!(b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E'))
})
.unwrap_or(json.len() - at);
let text = &json[at..at + len];
if !number(text) || !in_range(text) {
return Err(at);
}
at += len;
}
_ => return Err(at),
}
loop {
if n == 0 {
return if at == json.len() { Ok(()) } else { Err(at) };
}
at = space(at);
let object = open & 1 == 1;
match json.get(at) {
Some(b',') => {
at = space(at + 1);
if object {
at = valid_key(json, at, space)?;
}
break;
}
Some(b'}') if object => {}
Some(b']') if !object => {}
_ => return Err(at),
}
at += 1;
open >>= 1;
n -= 1;
}
}
}
#[cfg(feature = "json-keys")]
fn in_range(text: &[u8]) -> bool {
let float = text.len() > 308 || text.iter().any(|&b| matches!(b, b'e' | b'E'));
!float
|| std::str::from_utf8(text)
.ok()
.and_then(|t| t.parse::<f64>().ok())
.is_some_and(f64::is_finite)
}
#[cfg(feature = "json-keys")]
fn valid_key(json: &[u8], at: usize, space: impl Fn(usize) -> usize) -> Result<usize, usize> {
if json.get(at) != Some(&b'"') {
return Err(at);
}
let colon = space(valid_string(json, at)?);
if json.get(colon) != Some(&b':') {
return Err(colon);
}
Ok(colon + 1)
}
#[cfg(feature = "json-keys")]
fn valid_string(json: &[u8], at: usize) -> Result<usize, usize> {
let (end, _) = string_end(json, at + 1).map_err(|_| at)?;
let inner = &json[at + 1..end];
if std::str::from_utf8(inner).is_err() || unescape(inner, |_| {}).is_err() {
return Err(at);
}
Ok(end + 1)
}
fn number(text: &[u8]) -> bool {
let digits = |from: usize| {
text.get(from..)
.map_or(0, |t| t.iter().take_while(|b| b.is_ascii_digit()).count())
};
let mut at = usize::from(text.first() == Some(&b'-'));
match text.get(at) {
Some(b'0') => at += 1,
Some(b'1'..=b'9') => at += digits(at),
_ => return false,
}
if text.get(at) == Some(&b'.') {
let n = digits(at + 1);
if n == 0 {
return false;
}
at += 1 + n;
}
if matches!(text.get(at), Some(b'e' | b'E')) {
at += 1;
if matches!(text.get(at), Some(b'+' | b'-')) {
at += 1;
}
let n = digits(at);
if n == 0 {
return false;
}
at += n;
}
at == text.len()
}
struct Walk<'p, 'a, 'v> {
paths: &'p Paths,
json: &'a [u8],
at: usize,
visits: &'v mut [Visit],
key: &'v mut Vec<u8>,
}
impl Walk<'_, '_, '_> {
fn record(&mut self) {
self.space();
match self.json.get(self.at) {
Some(b'{') => {
self.visits[0].kind = Some(Kind::Object);
self.at += 1;
let _ = self.object(0, false);
}
Some(b'[') if self.paths.nodes[0].items_count > 0 => {
self.visits[0].kind = Some(Kind::Array);
self.at += 1;
let _ = self.array(0, false);
}
Some(&b) => self.visits[0].kind = Kind::of(b),
None => {}
}
}
fn object(&mut self, node: usize, to_end: bool) -> Result<bool, Malformed> {
let Node { first, count, .. } = self.paths.nodes[node];
let mut left = count;
self.space();
if self.peek() == Some(b'}') {
self.at += 1;
self.visits[node].closed = true;
return Ok(true);
}
loop {
if self.byte()? != b'"' {
return Err(Malformed);
}
let child = self.key(first, count)?;
self.space();
if self.byte()? != b':' {
return Err(Malformed);
}
self.space();
if let Some(child) = child {
let need = to_end || left > 1 || self.paths.nodes[child].wanted;
let ended = self.value(child, need)?;
left -= 1;
if left == 0 || !ended {
if to_end {
self.at = close(self.json, self.at)?;
}
return Ok(to_end);
}
} else {
self.skip()?;
}
self.space();
match self.byte()? {
b',' => self.space(),
b'}' => {
self.visits[node].closed = true;
return Ok(true);
}
_ => return Err(Malformed),
}
}
}
fn key(&mut self, first: usize, count: usize) -> Result<Option<usize>, Malformed> {
let json = self.json;
let paths = self.paths;
let start = self.at;
let (end, escaped) = string_end(json, start)?;
self.at = end + 1;
let edges = &paths.edges[first..first + count];
let edge = if escaped {
let limit = paths.longest;
let decoded = &mut *self.key;
decoded.clear();
let mut over = false;
unescape(&json[start..end], |part| {
if over || decoded.len() + part.len() > limit {
over = true;
} else {
decoded.extend_from_slice(part);
}
})?;
if over {
None
} else {
find(edges, decoded.as_slice())
}
} else {
match find(edges, &json[start..end]) {
Some(edge) if edge.control => return Err(Malformed),
found => found,
}
};
Ok(edge
.map(|edge| edge.node)
.filter(|&node| self.visits[node].kind.is_none()))
}
fn value(&mut self, node: usize, to_end: bool) -> Result<bool, Malformed> {
let start = self.at;
let kind = self.peek().and_then(Kind::of).ok_or(Malformed)?;
let Node {
count, items_count, ..
} = self.paths.nodes[node];
let walk = match kind {
Kind::Object => count > 0,
Kind::Array => items_count > 0,
_ => false,
};
if walk {
self.visits[node].kind = Some(kind);
self.at += 1;
let passed = if kind == Kind::Object {
self.object(node, to_end)?
} else {
self.array(node, to_end)?
};
if !passed {
return Ok(false);
}
} else {
self.pass(kind)?;
}
let visit = &mut self.visits[node];
visit.start = start;
visit.end = self.at;
visit.kind = Some(kind);
Ok(true)
}
fn array(&mut self, node: usize, to_end: bool) -> Result<bool, Malformed> {
let paths = self.paths;
let Node {
items_first,
items_count,
..
} = paths.nodes[node];
let items = &paths.items[items_first..items_first + items_count];
self.space();
if self.peek() == Some(b']') {
self.at += 1;
self.visits[node].closed = true;
return Ok(true);
}
let mut next = 0;
let mut i = 0;
loop {
let from = next;
while items.get(next).is_some_and(|&(index, _)| index == i) {
next += 1;
}
if from == next {
self.skip()?;
} else {
let start = self.at;
let mut ended = true;
for (k, &(_, child)) in items.iter().enumerate().take(next).skip(from) {
self.at = start;
let need = to_end || k + 1 < items.len() || paths.nodes[child].wanted;
ended = self.value(child, need)?;
}
if next == items.len() || !ended {
if to_end {
self.at = close(self.json, self.at)?;
}
return Ok(to_end);
}
}
self.space();
match self.byte()? {
b',' => self.space(),
b']' => {
self.visits[node].closed = true;
return Ok(true);
}
_ => return Err(Malformed),
}
i += 1;
}
}
fn skip(&mut self) -> Result<(), Malformed> {
let kind = self.peek().and_then(Kind::of).ok_or(Malformed)?;
self.pass(kind)
}
fn pass(&mut self, kind: Kind) -> Result<(), Malformed> {
self.at = value_end(self.json, self.at, kind)?;
Ok(())
}
#[inline]
fn space(&mut self) {
while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.json.get(self.at) {
self.at += 1;
}
}
#[inline]
fn peek(&self) -> Option<u8> {
self.json.get(self.at).copied()
}
#[inline]
fn byte(&mut self) -> Result<u8, Malformed> {
let b = self.peek().ok_or(Malformed)?;
self.at += 1;
Ok(b)
}
}
pub(super) fn value_end(json: &[u8], at: usize, kind: Kind) -> Result<usize, Malformed> {
match kind {
Kind::Object | Kind::Array => close(json, at + 1),
Kind::String => Ok(string_end(json, at + 1)?.0 + 1),
Kind::Number | Kind::Bool | Kind::Null => {
let rest = json.get(at..).ok_or(Malformed)?;
let len = rest
.iter()
.position(|&b| !(b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')))
.ok_or(Malformed)?;
if !matches!(rest[len], b',' | b'}' | b']' | b' ' | b'\t' | b'\n' | b'\r') {
return Err(Malformed);
}
Ok(at + len)
}
}
}
#[inline]
fn find<'e>(edges: &'e [Edge], key: &[u8]) -> Option<&'e Edge> {
edges
.binary_search_by(|edge| by_length(edge.key.as_bytes(), key))
.ok()
.map(|i| &edges[i])
}
pub(super) fn close(json: &[u8], from: usize) -> Result<usize, Malformed> {
let rest = json.get(from..).ok_or(Malformed)?;
let (blocks, tail) = rest.as_chunks::<BLOCK>();
let mut skip = Skip::default();
for (i, block) in blocks.iter().enumerate() {
if let Some(bit) = skip.block(Classes::of(block))? {
return Ok(from + i * BLOCK + bit + 1);
}
}
if tail.is_empty() {
return Err(Malformed);
}
let classes = json.last_chunk::<BLOCK>().map_or_else(
|| {
let mut padded = [0; BLOCK];
padded[..tail.len()].copy_from_slice(tail);
Classes::of(&padded)
},
|last| Classes::of(last).skip(BLOCK - tail.len()),
);
let bit = skip.block(classes)?.ok_or(Malformed)?;
Ok(from + blocks.len() * BLOCK + bit + 1)
}
struct Skip {
depth: usize,
in_string: u64,
escaped: u64,
}
impl Default for Skip {
fn default() -> Self {
Self {
depth: 1,
in_string: 0,
escaped: 0,
}
}
}
impl Skip {
#[inline]
fn block(&mut self, classes: Classes) -> Result<Option<usize>, Malformed> {
let Classes {
quotes,
backslashes,
opens,
closes,
} = classes;
let (escaped, next_escaped) = if backslashes == 0 {
(self.escaped, 0)
} else {
let potential = backslashes & !self.escaped;
let codes = ((potential << 1) | ODD_BITS).wrapping_sub(potential) ^ ODD_BITS;
(
codes ^ (backslashes | self.escaped),
(codes & backslashes) >> 63,
)
};
let strings = prefix_xor(quotes & !escaped) ^ self.in_string;
let shut = self.walk(opens & !strings, closes & !strings);
let read = shut.map_or(u64::MAX, |bit| u64::MAX >> (63 - bit));
if backslashes & !strings & read != 0 {
return Err(Malformed);
}
self.in_string = 0_u64.wrapping_sub(strings >> 63);
self.escaped = next_escaped;
Ok(shut)
}
#[inline]
const fn walk(&mut self, opens: u64, closes: u64) -> Option<usize> {
let n_close = closes.count_ones() as usize;
if n_close < self.depth {
self.depth = self.depth + opens.count_ones() as usize - n_close;
return None;
}
let mut marks = opens | closes;
while marks != 0 {
let bit = marks.trailing_zeros();
if (closes >> bit) & 1 == 1 {
self.depth -= 1;
if self.depth == 0 {
return Some(bit as usize);
}
} else {
self.depth += 1;
}
marks &= marks - 1;
}
None
}
}
#[cfg(test)]
pub(super) mod tests;