grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/record.rs
// Purpose:   One record abstraction: the value at a field path, typed, or which miss
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A record read by field path, whatever holds it: raw JSON bytes, a raw text
//! line, the fields a parser chain wrote, or raw XML bytes with `xml`.
//!
//! With `parse`, a [`LayerPlan`] reads a field or a body inside one as another
//! format, to any depth.
//!
//! [`Record`] finds the value at a path, reads below a value found once, and
//! types a value the way a cel context built from JSON types it. A path that
//! finds nothing says why, as a [`Miss`]. Each source is a small `Copy`
//! handle over borrowed data, and a reader generic over [`Record`] is
//! monomorphised per source, so the JSON path costs what a JSON-only reader
//! costs.
//!
//! ```
//! use grippo::record::{Json, Line, Miss, Record, Typed};
//!
//! let json = Json::new(br#"{"event":{"dns":{"type":"query"}}}"#);
//! let at = json.find(&["event", "dns", "type"])?;
//! assert_eq!(json.typed(at)?, Typed::Str("query".into()));
//! assert_eq!(json.find(&["host"]), Err(Miss::MissingRoot));
//!
//! let line = Line::new(b"login denied for bob");
//! let at = line.find(&["message"])?;
//! assert_eq!(line.typed(at)?, Typed::Str("login denied for bob".into()));
//! # Ok::<(), Miss>(())
//! ```

use std::borrow::Cow;

use crate::number::{Number, NumberReading};

#[cfg(feature = "parse")]
mod fields;
mod json;
mod line;
#[cfg(feature = "parse")]
mod nested;
#[cfg(feature = "xml")]
mod xml;

#[cfg(feature = "parse")]
pub use fields::FieldsAt;
#[cfg(all(feature = "parse", feature = "scrub"))]
pub(crate) use fields::{Spot, spot, write_strings};
pub use json::Json;
#[cfg(feature = "expr")]
pub(crate) use json::ReadPlan;
#[cfg(feature = "scrub")]
pub(crate) use json::{WalkBufs, Walked};
pub use line::Line;
#[cfg(all(feature = "parse", feature = "scrub"))]
pub(crate) use nested::FirstRead;
#[cfg(feature = "parse")]
pub use nested::{
    LayerCache, LayerError, LayerPlan, Layered, LayeredAt, MAX_LAYERS, Source, SourceAt,
};
#[cfg(feature = "xml")]
pub use xml::{Xml, XmlAt};

/// Why a path found no value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Miss {
    /// The path's first key isn't in the record.
    MissingRoot,
    /// A key below the first isn't in its parent.
    MissingField,
    /// A step reads into a value that isn't an object: a string, a number, a
    /// list or null.
    WrongParentType,
    /// The record is malformed where the path was read.
    Malformed,
}

/// A value as a cel context built from JSON types it: an integer is an int
/// when it fits `i64`, then a uint, then a double. [`Record::typed_exact`]
/// leaves a number past those as the string it was written as.
#[derive(Debug, Clone, PartialEq)]
pub enum Typed<'a> {
    /// A string, decoded, borrowed from the record where it can be.
    Str(Cow<'a, str>),
    /// An int.
    Int(i64),
    /// A uint.
    Uint(u64),
    /// A double.
    Double(f64),
    /// A bool.
    Bool(bool),
    /// A null.
    Null,
    /// A list. [`Record::text`] gives it as JSON.
    List,
    /// An object. [`Record::text`] gives it as JSON.
    Map,
}

/// A record whose values are read by field path.
///
/// A path is a slice of keys from the record's root, one key a step: `event`,
/// `dns`, `type` for cel's `event.dns.type`. A key is never split at a dot.
pub trait Record<'a>: Copy {
    /// Where a value sits, cheap to copy, so a path found once serves every
    /// read at or below it.
    type At: Copy;

    /// The value at `path` from the record's root.
    ///
    /// # Errors
    ///
    /// The [`Miss`] that stopped the read. An empty path is
    /// [`Miss::MissingRoot`].
    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<Self::At, Miss>;

    /// The value at `path` below `at`. An empty path is `at`.
    ///
    /// # Errors
    ///
    /// [`Miss::WrongParentType`] when a step reads into a value that isn't
    /// an object, [`Miss::MissingField`] when a key isn't there, and
    /// [`Miss::Malformed`] when the record is broken where it was read.
    fn find_below<K: AsRef<str>>(self, at: Self::At, path: &[K]) -> Result<Self::At, Miss>;

    /// The value at `at`, typed as a cel context built from JSON types it.
    ///
    /// A number is an int when it fits `i64`, then a uint, then the nearest
    /// double: [`NumberReading::Cel`]. A whole number past `u64` is rounded,
    /// so a store that must keep the digits reads [`Record::typed_exact`].
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the value can't be read.
    fn typed(self, at: Self::At) -> Result<Typed<'a>, Miss>;

    /// The value at `at`, typed without rounding an integer:
    /// [`NumberReading::Exact`].
    ///
    /// A number is an int when it fits `i64`, then a uint, and a float is a
    /// double. A number outside those, a whole number past `u64` or a float
    /// past `f64`, is a [`Typed::Str`] holding its text as written. Every
    /// other value is typed as [`Record::typed`] types it. A `Fields` value
    /// reads under its hint, as `FieldValue::number` does: `Int` is whole and
    /// `Float` is a double.
    ///
    /// An implementation has to say what it reads, so a source can't hand a
    /// store a rounded integer by leaving it out. A source whose values are
    /// all strings returns `typed`.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the value can't be read.
    fn typed_exact(self, at: Self::At) -> Result<Typed<'a>, Miss>;

    /// The value at `at` as text: a string decoded, a number or bool as the
    /// record writes it, a list or object as JSON.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the value can't be read.
    fn text(self, at: Self::At) -> Result<Cow<'a, str>, Miss>;

    /// The raw JSON bytes this record reads, and how a value's JSON text in
    /// them becomes an `At`, for a reader that finds many paths in one pass.
    #[doc(hidden)]
    #[allow(
        clippy::type_complexity,
        reason = "a byte slice and a converter, named once here"
    )]
    fn raw_json(self) -> Option<(&'a [u8], fn(&'a str) -> Self::At)> {
        None
    }
}

/// What a value is, as a walk finds it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Kind {
    /// A string.
    Str,
    /// A number.
    Number,
    /// A bool.
    Bool,
    /// A null.
    Null,
    /// A list.
    List,
    /// An object.
    Map,
}

/// One value a walk reaches.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Node<'a, At> {
    /// How many containers hold it below the record's root: 0 for a root
    /// member.
    pub depth: usize,
    /// Its key in an object, `None` for a list element.
    pub key: Option<Cow<'a, str>>,
    /// What it is.
    pub kind: Kind,
    /// Where it sits, for [`Record::text`] and a write-back.
    pub at: At,
}

/// A record whose every value can be reached.
///
/// A node's path is the keys of the nodes above it, then its own. A list
/// element adds no key, so it takes its list's path.
pub trait Walk<'a>: Record<'a> {
    /// Calls `visit` with every value in document order, a container before
    /// its members. The root's members are at depth 0. A JSON root that
    /// isn't an object is one keyless node at depth 0.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the record is broken anywhere, found before
    /// `visit` is first called.
    fn walk<F: FnMut(Node<'a, Self::At>)>(self, visit: F) -> Result<(), Miss>;

    /// Whether every part the last walk visited read as its format. `false`
    /// when a walk read a part as plain text instead: a `Hint::Json` field
    /// that doesn't parse, a layer that opened and didn't walk, or a layer
    /// its parser's hint or its format's own marker named that the format
    /// then refused. A scrub fails closed on a record that didn't read whole.
    fn read_whole(self) -> bool {
        true
    }

    /// The value at `at` as [`Record::text`] gives it, as bytes. A source
    /// that holds a string's bytes gives them as they are, UTF-8 or not.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the value can't be read.
    fn bytes(self, at: Self::At) -> Result<Cow<'a, [u8]>, Miss> {
        self.text(at).map(text_bytes)
    }
}

/// Text as its bytes, borrowed where it was.
fn text_bytes(text: Cow<'_, str>) -> Cow<'_, [u8]> {
    match text {
        Cow::Borrowed(s) => Cow::Borrowed(s.as_bytes()),
        Cow::Owned(s) => Cow::Owned(s.into_bytes()),
    }
}

/// A JSON object's keys, decoded, for a value expression's list `+` map.
#[cfg(feature = "expr")]
pub(crate) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
    json::object_keys(obj)
}

/// A number's text typed as a cel context built from JSON types it:
/// [`NumberReading::Cel`].
fn number(raw: &str) -> Result<Typed<'_>, Miss> {
    NumberReading::Cel
        .read(raw)
        .map(typed_number)
        .ok_or(Miss::Malformed)
}

/// A number's text typed losslessly: [`NumberReading::Exact`]. A decimal past
/// 64 bits or past `f64` is a string holding its text.
fn number_exact(raw: &str) -> Result<Typed<'_>, Miss> {
    match NumberReading::Exact.read(raw) {
        Some(number) => Ok(typed_number(number)),
        None if crate::number::decimal(raw.as_bytes()).is_some() => {
            Ok(Typed::Str(Cow::Borrowed(raw)))
        }
        None => Err(Miss::Malformed),
    }
}

/// A read number as the [`Typed`] value of its kind.
const fn typed_number<'a>(number: Number) -> Typed<'a> {
    match number {
        Number::Int(n) => Typed::Int(n),
        Number::UInt(n) => Typed::Uint(n),
        Number::Float(n) => Typed::Double(n),
    }
}

#[cfg(test)]
mod tests;