grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/json/literals.rs
// Purpose:   Many equals rows over field paths, one lookup per path
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Many `equals` rows over a record's fields: each path is read once, in one
//! pass, and each path's rows are one hash lookup on the value found.

#[cfg(feature = "parse")]
use std::borrow::Cow;
use std::collections::HashMap;

use super::paths::{Kind, Paths, Raw, Slots};
use crate::path::Path;

/// How a row compares the value at its path with its literal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Compare {
    /// The value's text as the record writes it: a string decoded, a number
    /// or `true` and `false` as written. So `"123"` matches `123` and
    /// `"123"`, and `"1.50"` matches `1.50` but not `1.5`.
    Text,
    /// A JSON string only, decoded, as CEL's `==` with a string literal.
    String,
    /// A number as `serde_json` prints it, as scalo's rules engine reads one:
    /// `1.50` reads `1.5`, `1e2` reads `100.0`, `-0` reads `-0.0` and an
    /// integer reads as written. The literal is read the same way when the
    /// index is built, so `"1.50"` matches `1.5` and `1.50`, and a literal
    /// that isn't a JSON number stays as written. A string or a bool matches
    /// the literal as written, as [`Compare::Text`] reads it.
    #[cfg(feature = "parse")]
    Number,
}

/// A value read by the caller, for [`LiteralIndex::matching_values`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Scalar<'a> {
    /// A string's contents, decoded.
    String(&'a str),
    /// A number's JSON text as the record writes it, such as `1.50`.
    Number(&'a str),
    /// `true` or `false`.
    Bool(bool),
}

/// Rows of `path equals literal`, answered together over one record.
///
/// Built once and `Send + Sync`, so one index serves every worker, each with
/// its own [`Slots`].
#[derive(Debug, Clone)]
pub struct LiteralIndex {
    paths: Paths,
    /// The distinct paths, in the order of `by_path`.
    path_list: Box<[Path]>,
    /// Each path's rows, in the order of `paths`.
    by_path: Vec<Rows>,
    len: usize,
}

#[derive(Debug, Clone, Default)]
struct Rows {
    /// Rows matching any value whose text is the literal.
    text: HashMap<Box<str>, Vec<usize>>,
    /// Rows matching only a string value.
    string: HashMap<Box<str>, Vec<usize>>,
    /// `Compare::Number` rows by their literal as written, for a string or a
    /// bool.
    #[cfg(feature = "parse")]
    number_text: HashMap<Box<str>, Vec<usize>>,
    /// `Compare::Number` rows by their literal as `serde_json` prints it, for
    /// a number.
    #[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])) {
        // Printing a number that isn't a plain integer allocates, so skip it
        // when no row would read the result.
        if !self.number.is_empty() {
            hit_on(&self.number, &number_form(text), hit);
        }
    }
}

/// A number's text as `serde_json` prints it. An integer of 1 to 18 digits,
/// other than `-0`, is already in that form, and text that isn't a JSON
/// number stays as written.
#[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 {
    /// Indexes `rows`, each a path, a literal and how they compare. A row's
    /// id is its position in `rows`. Equal paths share one read.
    #[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,
        }
    }

    /// The distinct paths the rows read, in the order
    /// [`LiteralIndex::matching_values`] takes their values.
    #[must_use]
    pub fn paths(&self) -> &[Path] {
        &self.path_list
    }

    /// The number of rows.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Whether there are no rows.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Every row true on `json`, by id, in order, into `out`, which is
    /// cleared first. A path that's missing, null, an object or an array, or
    /// malformed where it was read, matches no row.
    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();
        }
    }

    /// The first row true on `json`, as a rules table that stops at its
    /// first match reads it.
    #[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
    }

    /// As [`LiteralIndex::matching`], on values the caller has read: one per
    /// path of [`LiteralIndex::paths`], in order, `None` where a path has no
    /// scalar. For a record whose fields come from somewhere other than its
    /// bytes.
    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();
        }
    }

    /// The rows on the path at `path`, an index into [`LiteralIndex::paths`],
    /// that `value` matches: `rows` called once per matching run of ids, each
    /// in row order, with nothing allocated. A path whose rows share one
    /// [`Compare`] gets at most one run. An index past the paths matches
    /// nothing.
    pub fn rows_with<'s>(&'s self, path: usize, value: Scalar<'_>, rows: impl FnMut(&'s [usize])) {
        if let Some(by_path) = self.by_path.get(path) {
            by_path.scalar_hits(value, rows);
        }
    }

    /// As [`LiteralIndex::first`], on values given as
    /// [`LiteralIndex::matching_values`] takes them.
    #[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;