grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/record/json.rs
// Purpose:   Raw JSON bytes as a record, read lazily with no value tree
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A JSON object's bytes as a [`Record`]. On x86-64 and aarch64 each read is
//! a sonic-rs lookup on the bytes, with UTF-8 checked only up to the value
//! read. sonic-rs builds nowhere else, so there each object on a path is read
//! with `serde_json`, and a fault anywhere in that object is `Malformed`.

use std::borrow::Cow;

use super::{Miss, Record, Typed, number};

/// Raw JSON bytes, read as a record. A record with duplicate keys is outside
/// what's defined.
#[derive(Debug, Clone, Copy)]
pub struct Json<'a> {
    bytes: &'a [u8],
}

impl<'a> Json<'a> {
    /// The record in `bytes`.
    #[must_use]
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }
}

impl<'a> Record<'a> for Json<'a> {
    /// The value's JSON text.
    type At = &'a str;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<&'a str, Miss> {
        let Some((first, rest)) = path.split_first() else {
            return Err(Miss::MissingRoot);
        };
        if let Some(raw) = backend::lookup(self.bytes, path) {
            return Ok(raw);
        }
        walk(root(self.bytes, first.as_ref())?, rest)
    }

    fn find_below<K: AsRef<str>>(self, at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
        below(at, path)
    }

    fn typed(self, at: &'a str) -> Result<Typed<'a>, Miss> {
        typed(at)
    }

    fn text(self, at: &'a str) -> Result<Cow<'a, str>, Miss> {
        text(at)
    }
}

/// Whether raw JSON text is an object.
fn is_object(raw: &str) -> bool {
    raw.as_bytes().first() == Some(&b'{')
}

/// The raw text of the root field `key` in the record `json`. A record that
/// isn't a JSON object has no root fields.
fn root<'a>(json: &'a [u8], key: &str) -> Result<&'a str, Miss> {
    let start = json.iter().position(|b| !b.is_ascii_whitespace());
    if start.map(|i| json[i]) != Some(b'{') {
        return Err(Miss::MissingRoot);
    }
    backend::root(json, key)?.ok_or(Miss::MissingRoot)
}

/// The raw text at `path` below the JSON value `obj`, one lookup when it's
/// there.
pub(super) fn below<'a, K: AsRef<str>>(obj: &'a str, path: &[K]) -> Result<&'a str, Miss> {
    if path.is_empty() {
        return Ok(obj);
    }
    if !is_object(obj) {
        return Err(Miss::WrongParentType);
    }
    if let Some(raw) = backend::lookup_str(obj, path) {
        return Ok(raw);
    }
    walk(obj, path)
}

/// Each key of `path` read in turn from `at`, naming the first miss.
fn walk<'a, K: AsRef<str>>(mut at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
    for key in path {
        if !is_object(at) {
            return Err(Miss::WrongParentType);
        }
        at = backend::member(at, key.as_ref())?.ok_or(Miss::MissingField)?;
    }
    Ok(at)
}

/// Types the raw JSON text of a value.
pub(super) fn typed(raw: &str) -> Result<Typed<'_>, Miss> {
    match raw.as_bytes().first() {
        Some(b'"') => string(raw).map(Typed::Str),
        Some(b't') => Ok(Typed::Bool(true)),
        Some(b'f') => Ok(Typed::Bool(false)),
        Some(b'n') => Ok(Typed::Null),
        Some(b'[') => Ok(Typed::List),
        Some(b'{') => Ok(Typed::Map),
        Some(b'-' | b'0'..=b'9') => number(raw),
        _ => Err(Miss::Malformed),
    }
}

/// The raw JSON text of a value as text: a string decoded, anything else as
/// written.
pub(super) fn text(raw: &str) -> Result<Cow<'_, str>, Miss> {
    if raw.as_bytes().first() == Some(&b'"') {
        string(raw)
    } else {
        Ok(Cow::Borrowed(raw))
    }
}

/// A JSON string's text decoded, borrowed when it holds no escape.
fn string(raw: &str) -> Result<Cow<'_, str>, Miss> {
    let inner = raw
        .get(1..raw.len().saturating_sub(1))
        .ok_or(Miss::Malformed)?;
    if memchr::memchr(b'\\', inner.as_bytes()).is_none() {
        Ok(Cow::Borrowed(inner))
    } else {
        backend::decode(raw).map(Cow::Owned)
    }
}

/// A JSON object's keys, decoded, in document order where sonic-rs builds
/// and in key order elsewhere.
#[cfg(feature = "expr")]
pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
    backend::object_keys(obj)
}

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
use simd as backend;

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
use portable as backend;

/// The reads on sonic-rs, which builds only for x86-64 and aarch64.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
mod simd {
    use std::borrow::Cow;

    use super::Miss;

    /// The raw text at `path` in `json`, when one lookup finds it in place.
    pub(super) fn lookup<'a, K: AsRef<str>>(json: &'a [u8], path: &[K]) -> Option<&'a str> {
        sonic_rs::get_from_slice(json, path.iter().map(AsRef::as_ref))
            .ok()
            .and_then(|v| borrowed(&v))
    }

    /// As [`lookup`] on text, with no UTF-8 check.
    pub(super) fn lookup_str<'a, K: AsRef<str>>(obj: &'a str, path: &[K]) -> Option<&'a str> {
        sonic_rs::get_from_str(obj, path.iter().map(AsRef::as_ref))
            .ok()
            .and_then(|v| borrowed(&v))
    }

    /// The value's raw text, when sonic-rs could hand it back in place.
    fn borrowed<'a>(v: &sonic_rs::LazyValue<'a>) -> Option<&'a str> {
        match v.as_raw_cow() {
            Cow::Borrowed(raw) => Some(raw),
            Cow::Owned(_) => None,
        }
    }

    /// The raw text of the root field `key`, `None` when it's absent.
    pub(super) fn root<'a>(json: &'a [u8], key: &str) -> Result<Option<&'a str>, Miss> {
        found(sonic_rs::get_from_slice(json, [key]))
    }

    /// The raw text of the value at `key` in the object `obj`.
    pub(super) fn member<'a>(obj: &'a str, key: &str) -> Result<Option<&'a str>, Miss> {
        found(sonic_rs::get_from_str(obj, [key]))
    }

    fn found(got: sonic_rs::Result<sonic_rs::LazyValue<'_>>) -> Result<Option<&str>, Miss> {
        match got {
            Ok(v) => match v.as_raw_cow() {
                Cow::Borrowed(raw) => Ok(Some(raw)),
                Cow::Owned(_) => Err(Miss::Malformed),
            },
            Err(e) if e.is_not_found() => Ok(None),
            Err(_) => Err(Miss::Malformed),
        }
    }

    /// A JSON string with an escape, decoded.
    pub(super) fn decode(raw: &str) -> Result<String, Miss> {
        sonic_rs::from_str(raw).map_err(|_| Miss::Malformed)
    }

    #[cfg(any(test, feature = "expr"))]
    pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
        sonic_rs::to_object_iter(obj)
            .map(|pair| {
                pair.map(|(key, _)| key.into_owned())
                    .map_err(|_| Miss::Malformed)
            })
            .collect()
    }
}

/// The reads on `serde_json`, for every target sonic-rs doesn't build on.
#[cfg(any(test, not(any(target_arch = "x86_64", target_arch = "aarch64"))))]
mod portable {
    use std::borrow::Cow;
    use std::collections::BTreeMap;

    use serde_json::value::RawValue;

    use super::Miss;

    /// Members by key, each value's raw text borrowed.
    type Members<'a> = BTreeMap<Cow<'a, str>, &'a RawValue>;

    /// No single lookup here: the caller reads the path key by key.
    pub(super) const fn lookup<'a, K: AsRef<str>>(_json: &'a [u8], _path: &[K]) -> Option<&'a str> {
        None
    }

    /// No single lookup here: the caller reads the path key by key.
    pub(super) const fn lookup_str<'a, K: AsRef<str>>(
        _obj: &'a str,
        _path: &[K],
    ) -> Option<&'a str> {
        None
    }

    /// The raw text of the root field `key`, `None` when it's absent.
    pub(super) fn root<'a>(json: &'a [u8], key: &str) -> Result<Option<&'a str>, Miss> {
        member(std::str::from_utf8(json).map_err(|_| Miss::Malformed)?, key)
    }

    /// The raw text of the value at `key` in the object `obj`.
    pub(super) fn member<'a>(obj: &'a str, key: &str) -> Result<Option<&'a str>, Miss> {
        let members: Members<'a> = serde_json::from_str(obj).map_err(|_| Miss::Malformed)?;
        Ok(members.get(key).map(|v| v.get()))
    }

    /// A JSON string with an escape, decoded.
    pub(super) fn decode(raw: &str) -> Result<String, Miss> {
        serde_json::from_str(raw).map_err(|_| Miss::Malformed)
    }

    #[cfg(any(test, feature = "expr"))]
    pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
        let members: Members<'_> = serde_json::from_str(obj).map_err(|_| Miss::Malformed)?;
        Ok(members.into_keys().map(Cow::into_owned).collect())
    }
}

#[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))]
mod tests {
    use super::{Miss, portable, simd};

    /// The `serde_json` reads give what the sonic-rs reads give, misses included.
    #[test]
    fn the_portable_reads_agree_with_sonic() {
        let objects = [
            r#"{"a":1,"b":{"c":"x"},"d":[1,2],"e":null}"#,
            r#" { "a" : "q\"r" , "b" : true } "#,
            "{}",
            r#"{"a":}"#,
            r#"{"a":1"#,
            "[1]",
        ];
        for obj in objects {
            for key in ["a", "b", "d", "e", "z"] {
                let want = simd::member(obj, key);
                let got = portable::member(obj, key);
                let malformed = Err(Miss::Malformed);
                // sonic-rs reads lazily, so a fault past the key it found is never seen.
                assert!(
                    got == want || got == malformed,
                    "{obj} {key}: {got:?} {want:?}"
                );
                if obj.starts_with('{') {
                    let root = (
                        simd::root(obj.as_bytes(), key),
                        portable::root(obj.as_bytes(), key),
                    );
                    assert!(
                        root.1 == root.0 || root.1 == malformed,
                        "{obj} {key}: {root:?}"
                    );
                }
            }
            if simd::object_keys(obj).is_ok() {
                let mut want = simd::object_keys(obj);
                if let Ok(keys) = want.as_mut() {
                    keys.sort();
                }
                assert_eq!(portable::object_keys(obj), want, "{obj}");
            }
        }
        for raw in [r#""a\nb""#, r#""\u00e9""#, r#""\q""#] {
            assert_eq!(portable::decode(raw), simd::decode(raw), "{raw}");
        }
        assert_eq!(portable::lookup(b"{}", &["a"]), None);
        assert_eq!(portable::lookup_str("{}", &["a"]), None);
    }
}