grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/record/fields.rs
// Purpose:   The fields a parser chain wrote, read as a nested record by dotted name
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Fields`] as a [`Record`]. A full name splits at every dot into a path, so
//! `syslog.host` is the key `host` in the object `syslog`. A name written more
//! than once is a list, a name with longer names below it is an object, and a
//! `Hint::Json` value is read as JSON, paths below it included.

use std::borrow::Cow;

use crate::parse::{FieldValue, Fields, Hint};

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

/// How deep an object built from dotted names may nest before it's refused
/// as malformed, so the build's recursion stays bounded.
const MAX_NESTING: usize = 64;

/// Where a value sits in [`Fields`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldsAt<'a>(Place<'a>);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Place<'a> {
    /// The field at this position, its name written once.
    One(usize),
    /// A name written more than once, its first position: a list.
    Many(usize),
    /// The names below a prefix: the first `len` bytes of this field's name.
    Object { witness: usize, len: usize },
    /// A value inside a `Hint::Json` field, its JSON text.
    Json(&'a str),
}

type Pairs<'v> = [(String, FieldValue<'v>)];

impl<'a, 'v: 'a> Record<'a> for &'a Fields<'v> {
    type At = FieldsAt<'a>;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<FieldsAt<'a>, Miss> {
        locate(self.as_slice(), None, path).map(FieldsAt)
    }

    fn find_below<K: AsRef<str>>(self, at: FieldsAt<'a>, path: &[K]) -> Result<FieldsAt<'a>, Miss> {
        if path.is_empty() {
            return Ok(at);
        }
        let fields = self.as_slice();
        let place = match at.0 {
            Place::One(i) => {
                let value = value(fields, i)?;
                if value.hint != Hint::Json {
                    return Err(Miss::WrongParentType);
                }
                Place::Json(json::below(utf8(value)?, path)?)
            }
            Place::Many(_) => return Err(Miss::WrongParentType),
            Place::Object { witness, len } => {
                locate(fields, Some(prefix(fields, witness, len)?), path)?
            }
            Place::Json(raw) => Place::Json(json::below(raw, path)?),
        };
        Ok(FieldsAt(place))
    }

    fn typed(self, at: FieldsAt<'a>) -> Result<Typed<'a>, Miss> {
        match at.0 {
            Place::One(i) => typed(value(self.as_slice(), i)?),
            Place::Many(_) => Ok(Typed::List),
            Place::Object { .. } => Ok(Typed::Map),
            Place::Json(raw) => json::typed(raw),
        }
    }

    fn text(self, at: FieldsAt<'a>) -> Result<Cow<'a, str>, Miss> {
        let fields = self.as_slice();
        match at.0 {
            Place::One(i) => {
                let value = value(fields, i)?;
                let raw = utf8(value)?;
                if value.hint == Hint::Json {
                    json::text(raw)
                } else {
                    Ok(Cow::Borrowed(raw))
                }
            }
            Place::Json(raw) => json::text(raw),
            place => {
                let mut out = String::new();
                write_json(fields, place, 0, &mut out)?;
                Ok(Cow::Owned(out))
            }
        }
    }
}

/// How a field's name stands to a path below the same prefix.
enum Relation {
    /// Unrelated.
    None,
    /// The first key matches and nothing more.
    Root,
    /// The name is the path.
    Exact,
    /// The name runs on below the path, which takes this many of its bytes.
    Below(usize),
    /// The name is the path's first this many keys.
    Into(usize),
}

/// How `rest`, a name with the prefix taken off, stands to `path`. A key
/// holding a dot never matches, since a name splits at every dot.
fn relate<K: AsRef<str>>(rest: &str, path: &[K]) -> Relation {
    let mut left = rest;
    for (i, key) in path.iter().enumerate() {
        let key = key.as_ref();
        let after = match left.strip_prefix(key) {
            Some(after) if !key.contains('.') && (after.is_empty() || after.starts_with('.')) => {
                after
            }
            _ if i == 0 => return Relation::None,
            _ => return Relation::Root,
        };
        if after.is_empty() {
            return if i + 1 == path.len() {
                Relation::Exact
            } else {
                Relation::Into(i + 1)
            };
        }
        left = &after[1..];
    }
    Relation::Below(rest.len() - left.len() - 1)
}

/// The name with `prefix` and its dot taken off, or `None` outside it.
fn under<'n>(name: &'n str, prefix: Option<&str>) -> Option<&'n str> {
    match prefix {
        None => Some(name),
        Some(p) => name.strip_prefix(p)?.strip_prefix('.'),
    }
}

/// The place `path` names below `prefix`, `None` for the record's root. A
/// name that is the path wins over longer names below it.
fn locate<'a, K: AsRef<str>>(
    fields: &'a Pairs<'_>,
    prefix: Option<&str>,
    path: &[K],
) -> Result<Place<'a>, Miss> {
    if path.is_empty() {
        return Err(Miss::MissingRoot);
    }
    let mut exact: Option<(usize, bool)> = None;
    let mut below: Option<(usize, usize)> = None;
    let mut into: Option<(usize, usize)> = None;
    let mut root = false;
    for (i, (name, _)) in fields.iter().enumerate() {
        let Some(rest) = under(name, prefix) else {
            continue;
        };
        match relate(rest, path) {
            Relation::None => {}
            Relation::Root => root = true,
            Relation::Exact => match &mut exact {
                Some((_, many)) => *many = true,
                None => exact = Some((i, false)),
            },
            Relation::Below(taken) => {
                below.get_or_insert((i, name.len() - rest.len() + taken));
            }
            Relation::Into(keys) => {
                if into.is_none_or(|(_, k)| keys < k) {
                    into = Some((i, keys));
                }
            }
        }
    }
    if let Some((i, many)) = exact {
        return Ok(if many { Place::Many(i) } else { Place::One(i) });
    }
    if let Some((witness, len)) = below {
        return Ok(Place::Object { witness, len });
    }
    if let Some((i, keys)) = into {
        let (name, value) = &fields[i];
        let repeated = fields.iter().filter(|(n, _)| n == name).nth(1).is_some();
        if repeated || value.hint != Hint::Json {
            return Err(Miss::WrongParentType);
        }
        return json::below(utf8(value)?, &path[keys..]).map(Place::Json);
    }
    Err(if prefix.is_none() && !root {
        Miss::MissingRoot
    } else {
        Miss::MissingField
    })
}

/// The value at position `i`. An `At` from another record may point past
/// this one's end.
fn value<'f, 'v>(fields: &'f Pairs<'v>, i: usize) -> Result<&'f FieldValue<'v>, Miss> {
    fields.get(i).map(|(_, v)| v).ok_or(Miss::Malformed)
}

/// The first `len` bytes of the name at position `witness`.
fn prefix<'f>(fields: &'f Pairs<'_>, witness: usize, len: usize) -> Result<&'f str, Miss> {
    fields
        .get(witness)
        .and_then(|(name, _)| name.get(..len))
        .ok_or(Miss::Malformed)
}

/// A field's bytes as text.
fn utf8<'a>(value: &'a FieldValue<'_>) -> Result<&'a str, Miss> {
    std::str::from_utf8(&value.bytes).map_err(|_| Miss::Malformed)
}

/// A field's value typed by its hint. A number or bool hint whose text isn't
/// one is a string, as the parser wrote it.
fn typed<'a>(value: &'a FieldValue<'_>) -> Result<Typed<'a>, Miss> {
    let text = utf8(value)?;
    Ok(match value.hint {
        Hint::Json => return json::typed(text),
        Hint::Int | Hint::Float => number(text).unwrap_or(Typed::Str(Cow::Borrowed(text))),
        Hint::Bool => match text {
            "true" => Typed::Bool(true),
            "false" => Typed::Bool(false),
            _ => Typed::Str(Cow::Borrowed(text)),
        },
        _ => Typed::Str(Cow::Borrowed(text)),
    })
}

/// Appends the JSON for `place`.
fn write_json(
    fields: &Pairs<'_>,
    place: Place<'_>,
    depth: usize,
    out: &mut String,
) -> Result<(), Miss> {
    if depth > MAX_NESTING {
        return Err(Miss::Malformed);
    }
    match place {
        Place::One(i) => write_value(value(fields, i)?, out),
        Place::Json(raw) => {
            out.push_str(raw);
            Ok(())
        }
        Place::Many(first) => {
            let name = &fields.get(first).ok_or(Miss::Malformed)?.0;
            out.push('[');
            for (k, (_, value)) in fields.iter().filter(|(n, _)| n == name).enumerate() {
                if k > 0 {
                    out.push(',');
                }
                write_value(value, out)?;
            }
            out.push(']');
            Ok(())
        }
        Place::Object { witness, len } => {
            let prefix = prefix(fields, witness, len)?;
            let mut keys: Vec<&str> = Vec::new();
            for (name, _) in fields {
                if let Some(rest) = under(name, Some(prefix)) {
                    let key = rest.split('.').next().unwrap_or(rest);
                    if !keys.contains(&key) {
                        keys.push(key);
                    }
                }
            }
            out.push('{');
            for (k, key) in keys.iter().enumerate() {
                if k > 0 {
                    out.push(',');
                }
                write_string(key, out)?;
                out.push(':');
                let child = locate(fields, Some(prefix), &[key])?;
                write_json(fields, child, depth + 1, out)?;
            }
            out.push('}');
            Ok(())
        }
    }
}

/// Appends one field's value as JSON, typed as [`Record::typed`] types it.
fn write_value(value: &FieldValue<'_>, out: &mut String) -> Result<(), Miss> {
    if value.hint == Hint::Json {
        out.push_str(utf8(value)?);
        return Ok(());
    }
    match typed(value)? {
        Typed::Str(s) => write_string(&s, out),
        Typed::Int(n) => {
            out.push_str(&n.to_string());
            Ok(())
        }
        Typed::Uint(n) => {
            out.push_str(&n.to_string());
            Ok(())
        }
        Typed::Double(n) => {
            out.push_str(&serde_json::to_string(&n).map_err(|_| Miss::Malformed)?);
            Ok(())
        }
        Typed::Bool(b) => {
            out.push_str(if b { "true" } else { "false" });
            Ok(())
        }
        Typed::Null => {
            out.push_str("null");
            Ok(())
        }
        Typed::List | Typed::Map => Err(Miss::Malformed),
    }
}

/// Appends `s` as a JSON string.
fn write_string(s: &str, out: &mut String) -> Result<(), Miss> {
    out.push_str(&serde_json::to_string(s).map_err(|_| Miss::Malformed)?);
    Ok(())
}