grippo 0.1.3

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/record/line.rs
// Purpose:   A raw text line as a record of one string field
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A line with no parse as a [`Record`]: the whole line is one string field,
//! `message` unless named otherwise.

use std::borrow::Cow;

use super::{Kind, Miss, Node, Record, Typed, Walk};

/// A raw text line, read as the record `{"message": "<line>"}`.
#[derive(Debug, Clone, Copy)]
pub struct Line<'a> {
    text: &'a [u8],
    name: &'a str,
}

impl<'a> Line<'a> {
    /// The line in `text`, as the field `message`.
    #[must_use]
    pub const fn new(text: &'a [u8]) -> Self {
        Self::named(text, "message")
    }

    /// The line in `text`, as the field `name`.
    #[must_use]
    pub const fn named(text: &'a [u8], name: &'a str) -> Self {
        Self { text, name }
    }
}

impl<'a> Record<'a> for Line<'a> {
    /// The line's one field is the only value there is.
    type At = ();

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<(), Miss> {
        match path.split_first() {
            Some((first, rest)) if first.as_ref() == self.name => self.find_below((), rest),
            _ => Err(Miss::MissingRoot),
        }
    }

    fn find_below<K: AsRef<str>>(self, (): (), path: &[K]) -> Result<(), Miss> {
        if path.is_empty() {
            Ok(())
        } else {
            Err(Miss::WrongParentType)
        }
    }

    fn typed(self, (): ()) -> Result<Typed<'a>, Miss> {
        self.text(()).map(Typed::Str)
    }

    fn text(self, (): ()) -> Result<Cow<'a, str>, Miss> {
        std::str::from_utf8(self.text)
            .map(Cow::Borrowed)
            .map_err(|_| Miss::Malformed)
    }
}

impl<'a> Walk<'a> for Line<'a> {
    fn walk<F: FnMut(Node<'a, ()>)>(self, mut visit: F) -> Result<(), Miss> {
        visit(Node {
            depth: 0,
            key: Some(Cow::Borrowed(self.name)),
            kind: Kind::Str,
            at: (),
        });
        Ok(())
    }

    fn bytes(self, (): ()) -> Result<Cow<'a, [u8]>, Miss> {
        Ok(Cow::Borrowed(self.text))
    }
}