#[cfg(feature = "parse")]
use std::borrow::Cow;
use std::collections::HashMap;
use super::paths::{Kind, Paths, Raw, Slots};
use crate::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Compare {
Text,
String,
#[cfg(feature = "parse")]
Number,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Scalar<'a> {
String(&'a str),
Number(&'a str),
Bool(bool),
}
#[derive(Debug, Clone)]
pub struct LiteralIndex {
paths: Paths,
path_list: Box<[Path]>,
by_path: Vec<Rows>,
len: usize,
}
#[derive(Debug, Clone, Default)]
struct Rows {
text: HashMap<Box<str>, Vec<usize>>,
string: HashMap<Box<str>, Vec<usize>>,
#[cfg(feature = "parse")]
number_text: HashMap<Box<str>, Vec<usize>>,
#[cfg(feature = "parse")]
number: HashMap<Box<str>, Vec<usize>>,
}
fn hit_on<'s>(
map: &'s HashMap<Box<str>, Vec<usize>>,
key: &str,
hit: &mut impl FnMut(&'s [usize]),
) {
if let Some(ids) = map.get(key) {
hit(ids);
}
}
impl Rows {
fn hits<'s>(&'s self, raw: Raw<'_>, hit: impl FnMut(&'s [usize])) {
match raw.kind() {
Kind::String => {
if let Some(s) = raw.to_str() {
self.scalar_hits(Scalar::String(&s), hit);
}
}
Kind::Bool => self.scalar_hits(Scalar::Bool(raw.text() == "true"), hit),
Kind::Number => self.scalar_hits(Scalar::Number(raw.text()), hit),
Kind::Object | Kind::Array | Kind::Null => {}
}
}
fn scalar_hits<'s>(&'s self, value: Scalar<'_>, mut hit: impl FnMut(&'s [usize])) {
match value {
Scalar::String(s) => {
hit_on(&self.text, s, &mut hit);
hit_on(&self.string, s, &mut hit);
#[cfg(feature = "parse")]
hit_on(&self.number_text, s, &mut hit);
}
Scalar::Bool(b) => {
let text = if b { "true" } else { "false" };
hit_on(&self.text, text, &mut hit);
#[cfg(feature = "parse")]
hit_on(&self.number_text, text, &mut hit);
}
Scalar::Number(n) => {
hit_on(&self.text, n, &mut hit);
#[cfg(feature = "parse")]
self.number_hits(n, &mut hit);
}
}
}
#[cfg(feature = "parse")]
fn number_hits<'s>(&'s self, text: &str, hit: &mut impl FnMut(&'s [usize])) {
if !self.number.is_empty() {
hit_on(&self.number, &number_form(text), hit);
}
}
}
#[cfg(feature = "parse")]
fn number_form(text: &str) -> Cow<'_, str> {
let digits = text.strip_prefix('-').unwrap_or(text);
let plain_integer = (1..=18).contains(&digits.len())
&& digits.bytes().all(|b| b.is_ascii_digit())
&& (digits == "0" || !digits.starts_with('0'))
&& text != "-0";
if plain_integer {
return Cow::Borrowed(text);
}
text.parse::<serde_json::Number>()
.map_or(Cow::Borrowed(text), |number| Cow::Owned(number.to_string()))
}
impl LiteralIndex {
#[must_use]
pub fn new<I, L>(rows: I) -> Self
where
I: IntoIterator<Item = (Path, L, Compare)>,
L: Into<Box<str>>,
{
let mut paths: Vec<Path> = Vec::new();
let mut by_path: Vec<Rows> = Vec::new();
let mut len = 0;
for (id, (path, literal, compare)) in rows.into_iter().enumerate() {
let at = paths.iter().position(|p| *p == path).unwrap_or_else(|| {
paths.push(path);
by_path.push(Rows::default());
paths.len() - 1
});
let literal: Box<str> = literal.into();
let rows = &mut by_path[at];
let map = match compare {
Compare::Text => &mut rows.text,
Compare::String => &mut rows.string,
#[cfg(feature = "parse")]
Compare::Number => {
let printed: Box<str> = number_form(&literal).into();
rows.number.entry(printed).or_default().push(id);
&mut rows.number_text
}
};
map.entry(literal).or_default().push(id);
len = id + 1;
}
Self {
path_list: paths.clone().into(),
paths: Paths::new(paths),
by_path,
len,
}
}
#[must_use]
pub fn paths(&self) -> &[Path] {
&self.path_list
}
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
pub fn matching(&self, json: &[u8], slots: &mut Slots, out: &mut Vec<usize>) {
out.clear();
let mut lists = 0;
let values = self.paths.read(json, slots);
for (rows, slot) in self.by_path.iter().zip(values.iter()) {
if let Some(raw) = slot.found() {
rows.hits(raw, |ids| {
out.extend_from_slice(ids);
lists += 1;
});
}
}
if lists > 1 {
out.sort_unstable();
}
}
#[must_use]
pub fn first(&self, json: &[u8], slots: &mut Slots) -> Option<usize> {
let mut first: Option<usize> = None;
let values = self.paths.read(json, slots);
for (rows, slot) in self.by_path.iter().zip(values.iter()) {
if let Some(raw) = slot.found() {
rows.hits(raw, |ids| {
if let Some(&id) = ids.first() {
first = Some(first.map_or(id, |f| f.min(id)));
}
});
}
}
first
}
pub fn matching_values<'v>(
&self,
values: impl IntoIterator<Item = Option<Scalar<'v>>>,
out: &mut Vec<usize>,
) {
out.clear();
let mut lists = 0;
for (rows, value) in self.by_path.iter().zip(values) {
if let Some(value) = value {
rows.scalar_hits(value, |ids| {
out.extend_from_slice(ids);
lists += 1;
});
}
}
if lists > 1 {
out.sort_unstable();
}
}
#[must_use]
pub fn first_value<'v>(
&self,
values: impl IntoIterator<Item = Option<Scalar<'v>>>,
) -> Option<usize> {
let mut first: Option<usize> = None;
for (rows, value) in self.by_path.iter().zip(values) {
if let Some(value) = value {
rows.scalar_hits(value, |ids| {
if let Some(&id) = ids.first() {
first = Some(first.map_or(id, |f| f.min(id)));
}
});
}
}
first
}
}
#[cfg(test)]
mod tests;