grippo 0.1.1

Parse, match and scrub data at scale.
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`.
//!
//! [`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;

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

#[cfg(feature = "parse")]
pub use fields::FieldsAt;
#[cfg(all(feature = "parse", feature = "scrub"))]
pub(crate) use fields::{spot, write_strings};
pub use json::Json;
pub use line::Line;
#[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.
#[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.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the value can't be read.
    fn typed(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>;
}

/// 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>;

    /// 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 by grippo's rule: an int when it fits `i64`, then a
/// uint, then a double.
fn number(raw: &str) -> Result<Typed<'_>, Miss> {
    let float = || {
        raw.parse::<f64>()
            .map(Typed::Double)
            .map_err(|_| Miss::Malformed)
    };
    if raw.bytes().any(|b| matches!(b, b'.' | b'e' | b'E')) {
        return float();
    }
    if raw.starts_with('-') {
        return raw.parse::<i64>().map(Typed::Int).or_else(|_| float());
    }
    raw.parse::<u64>().map_or_else(
        |_| float(),
        |u| Ok(i64::try_from(u).map_or(Typed::Uint(u), Typed::Int)),
    )
}

#[cfg(test)]
mod tests;