grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/record/nested/write.rs
// Purpose:   A layered record written back, innermost layer first, each in its own escaping
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Each layer's edits are spliced into its bytes, then those bytes replace
//! the value the layer was read from, in the layer before's own escaping.

use std::borrow::Cow;
use std::ops::Range;

use memchr::memmem;

use crate::parse::{FieldValue, Fields, Parsed, Parser};
use crate::record::fields::Spot;
use crate::record::{json, spot};

#[cfg(feature = "xml")]
use super::XmlAt;
use super::{Layered, LayeredAt, Miss, Opened, Place, Read, Record, Source, SourceAt, Src, SrcAt};

/// A value's new bytes, and whether they go in as they are rather than as
/// the layer before's string.
struct Put {
    bytes: Vec<u8>,
    raw: bool,
}

impl<'a> Layered<'a, Source<'a>> {
    /// Writes the record to `out` with each value in `edits` replaced by a
    /// string of the bytes given for it. Each layer that changed is written
    /// back into the value it was read from: as a JSON string, as escaped XML
    /// text, or as its parser's [`Parser::escape_value`] writes it, checked
    /// by parsing the layer again. A layer's whole record replaced takes its value's place.
    ///
    /// Each `At` is from this record, as [`crate::record::Walk::walk`] gives
    /// them, none inside another. The record is one [`super::LayerPlan::open`]
    /// gave.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when an `At` isn't from this record, two overlap,
    /// a parser refuses to escape a value, or a parser's layer doesn't read
    /// back as written, with `out` left as it was.
    pub fn splice<B: AsRef<[u8]>>(
        self,
        edits: &[(LayeredAt<'a, SourceAt<'a>>, B)],
        out: &mut Vec<u8>,
    ) -> Result<(), Miss> {
        let mark = out.len();
        self.write(edits, out).inspect_err(|_| out.truncate(mark))
    }

    fn write<B: AsRef<[u8]>>(
        self,
        edits: &[(LayeredAt<'a, SourceAt<'a>>, B)],
        out: &mut Vec<u8>,
    ) -> Result<(), Miss> {
        let n = self.layers.layers.len();
        let mut puts: Vec<Vec<(SourceAt<'a>, Put)>> = (0..n).map(|_| Vec::new()).collect();
        let mut whole: Vec<Option<Vec<u8>>> = vec![None; n];
        let mut bodies: Vec<Option<Vec<u8>>> = vec![None; n];
        for (at, bytes) in edits {
            let put = Put {
                bytes: bytes.as_ref().to_vec(),
                raw: false,
            };
            match at.place {
                Place::Base(at) => puts[0].push((at, put)),
                Place::Root(k) => {
                    *whole.get_mut(usize::from(k)).ok_or(Miss::Malformed)? = Some(put.bytes);
                }
                Place::Inner(k, at) => {
                    puts.get_mut(usize::from(k))
                        .ok_or(Miss::Malformed)?
                        .push((at, put));
                }
            }
        }
        for k in (1..n).rev() {
            let put = if let Some(bytes) = whole[k].take() {
                Put { bytes, raw: false }
            } else if puts[k].is_empty() && bodies[k].is_none() {
                continue;
            } else {
                let opened = self.opened(k).ok_or(Miss::Malformed)?;
                let mut bytes = Vec::with_capacity(opened.bytes.len() + 32);
                let body = bodies[k].take();
                self.write_layer(k, opened, &puts[k], body.as_deref(), &mut bytes)?;
                Put { bytes, raw: true }
            };
            let layer = &self.layers.layers[k];
            if layer.body {
                bodies[k - 1] = Some(put.bytes);
                continue;
            }
            let parent = self.opened(k - 1).ok_or(Miss::Malformed)?;
            let anchor = Source(parent.source).find(&layer.mount)?;
            // A layer read from a JSON string goes back as one, and from raw JSON as it is.
            let raw = put.raw && matches!(anchor.0, SrcAt::Json(text) if !text.starts_with('"'));
            puts[k - 1].push((
                anchor,
                Put {
                    bytes: put.bytes,
                    raw,
                },
            ));
        }
        let base = self.opened(0).ok_or(Miss::Malformed)?;
        let body = bodies[0].take();
        self.write_layer(0, base, &puts[0], body.as_deref(), out)
    }

    /// Layer `k`'s bytes with `puts` written in, and its body replaced.
    fn write_layer(
        self,
        k: usize,
        opened: Opened<'a>,
        puts: &[(SourceAt<'a>, Put)],
        body: Option<&[u8]>,
        out: &mut Vec<u8>,
    ) -> Result<(), Miss> {
        match opened.source {
            Src::Json(_) if body.is_none() => {
                let mut spans = Vec::with_capacity(puts.len());
                for (at, put) in puts {
                    let SrcAt::Json(raw) = at.0 else {
                        return Err(Miss::Malformed);
                    };
                    let span = within(opened.bytes, raw.as_bytes()).ok_or(Miss::Malformed)?;
                    let mut text = Vec::with_capacity(put.bytes.len() + 2);
                    if put.raw {
                        text.extend_from_slice(&put.bytes);
                    } else {
                        json::push_string(&mut text, &put.bytes);
                    }
                    spans.push((span, text));
                }
                splice(opened.bytes, &mut spans, out)
            }
            #[cfg(feature = "xml")]
            Src::Xml(xml) if body.is_none() => {
                let edits = puts
                    .iter()
                    .map(|(at, put)| match at.0 {
                        SrcAt::Xml(at) => Ok((at, put.bytes.as_slice())),
                        _ => Err(Miss::Malformed),
                    })
                    .collect::<Result<Vec<(XmlAt, &[u8])>, Miss>>()?;
                xml.splice_text(&edits, out)
            }
            Src::Fields(fields) => self.write_fields(k, opened, fields, puts, body, out),
            _ => Err(Miss::Malformed),
        }
    }

    /// A parser's layer with `puts` and `body` written in, then parsed again
    /// to check every field reads back as written.
    fn write_fields(
        self,
        k: usize,
        opened: Opened<'a>,
        fields: &'a Fields<'a>,
        puts: &[(SourceAt<'a>, Put)],
        body: Option<&[u8]>,
        out: &mut Vec<u8>,
    ) -> Result<(), Miss> {
        let format = self
            .layers
            .layers
            .get(k)
            .and_then(|l| l.formats.get(opened.format))
            .ok_or(Miss::Malformed)?;
        let Read::Parser(parser) = &format.read else {
            return Err(Miss::Malformed);
        };
        // Writing back through a decoder would need its bytes encoded again.
        if parser.decodes() {
            return Err(Miss::Malformed);
        }
        let all = fields.as_slice();
        let parser = parser.as_ref();
        let mut spans: Vec<(Range<usize>, Vec<u8>)> = Vec::new();
        let mut reads: Vec<(usize, Cow<'_, [u8]>)> = Vec::new();
        let mut insides: Vec<(usize, Range<usize>, &[u8])> = Vec::new();
        for (at, put) in puts {
            let SrcAt::Fields(at) = at.0 else {
                return Err(Miss::Malformed);
            };
            match spot(fields, at)? {
                Spot::One(i) => reads.push((i, Cow::Borrowed(&put.bytes))),
                Spot::Many(first) => {
                    let name = &all.get(first).ok_or(Miss::Malformed)?.0;
                    for (i, (n, _)) in all.iter().enumerate() {
                        if n == name {
                            reads.push((i, Cow::Borrowed(&put.bytes)));
                        }
                    }
                }
                Spot::Inside { field, span } => insides.push((field, span, &put.bytes)),
                Spot::Object { .. } => return Err(Miss::Malformed),
            }
        }
        for (i, bytes) in &reads {
            let span = field_span(parser, opened.bytes, all, *i)?;
            let mut text = Vec::with_capacity(bytes.len() + 2);
            let span = parser
                .escape_value(opened.bytes, *i, span, bytes, &mut text)
                .ok_or(Miss::Malformed)?;
            spans.push((span, text));
        }
        // A JSON field's text goes back as it was lent, so a string inside it
        // is spliced in place and the field keeps its JSON type.
        insides.sort_unstable_by_key(|(field, span, _)| (*field, span.start));
        for group in insides.chunk_by(|a, b| a.0 == b.0) {
            let field = group[0].0;
            let Cow::Borrowed(raw) = all.get(field).ok_or(Miss::Malformed)?.1.bytes else {
                return Err(Miss::Malformed);
            };
            let at = within(opened.bytes, raw).ok_or(Miss::Malformed)?;
            let mut joined = Vec::with_capacity(raw.len() + 16 * group.len());
            let mut copied = 0;
            for (_, span, bytes) in group {
                joined.extend_from_slice(raw.get(copied..span.start).ok_or(Miss::Malformed)?);
                let mut string = Vec::with_capacity(bytes.len() + 2);
                json::push_string(&mut string, bytes);
                joined.extend_from_slice(&string);
                spans.push((at.start + span.start..at.start + span.end, string));
                copied = span.end;
            }
            joined.extend_from_slice(raw.get(copied..).ok_or(Miss::Malformed)?);
            reads.push((field, Cow::Owned(joined)));
        }
        if let Some(body) = body {
            let lent = opened.body.ok_or(Miss::Malformed)?;
            let at = within(opened.bytes, lent).ok_or(Miss::Malformed)?;
            spans.push((at, body.to_vec()));
        }
        let mark = out.len();
        splice(opened.bytes, &mut spans, out)?;
        if reads_back(parser, all, &out[mark..], &reads, body) {
            Ok(())
        } else {
            Err(Miss::Malformed)
        }
    }
}

/// Whether `written` parses to fields of the same names as `before`, each
/// field in `reads` holding its bytes, and the body `body` when given.
fn reads_back(
    parser: &dyn Parser,
    before: &[(String, FieldValue<'_>)],
    written: &[u8],
    reads: &[(usize, Cow<'_, [u8]>)],
    body: Option<&[u8]>,
) -> bool {
    let mut again = Fields::new();
    let span = match parser.parse(written, &mut again) {
        Ok(Parsed::Done) => None,
        Ok(Parsed::Body { span, .. }) => Some(span),
        _ => return false,
    };
    let after = again.as_slice();
    after.len() == before.len()
        && after.iter().zip(before).all(|(a, b)| a.0 == b.0)
        && reads
            .iter()
            .all(|(i, want)| after.get(*i).is_some_and(|(_, v)| *v.bytes == **want))
        && body.is_none_or(|b| span.and_then(|s| written.get(s)) == Some(b))
}

/// Where field `i`'s value is written in `bytes`: where its bytes are, when
/// the parser lent them, else its escaped form after the last lent value
/// before it.
fn field_span(
    parser: &dyn Parser,
    bytes: &[u8],
    all: &[(String, FieldValue<'_>)],
    i: usize,
) -> Result<Range<usize>, Miss> {
    let value = &all.get(i).ok_or(Miss::Malformed)?.1;
    if let Cow::Borrowed(lent) = &value.bytes
        && let Some(span) = within(bytes, lent)
    {
        return Ok(span);
    }
    let from = all[..i]
        .iter()
        .rev()
        .find_map(|(_, v)| match &v.bytes {
            Cow::Borrowed(lent) => within(bytes, lent),
            Cow::Owned(_) => None,
        })
        .map_or(0, |span| span.end);
    let mut escaped = Vec::with_capacity(value.bytes.len());
    parser
        .escape_value(&[], i, 0..0, &value.bytes, &mut escaped)
        .ok_or(Miss::Malformed)?;
    if escaped.is_empty() {
        return Err(Miss::Malformed);
    }
    let at = memmem::find(&bytes[from..], &escaped).ok_or(Miss::Malformed)? + from;
    Ok(at..at + escaped.len())
}

/// Where `inner` sits in `outer`, `None` when it isn't inside it.
fn within(outer: &[u8], inner: &[u8]) -> Option<Range<usize>> {
    let start = inner.as_ptr().addr().checked_sub(outer.as_ptr().addr())?;
    let end = start.checked_add(inner.len())?;
    (end <= outer.len()).then_some(start..end)
}

/// Appends `bytes` with each span replaced by its text.
fn splice(
    bytes: &[u8],
    spans: &mut [(Range<usize>, Vec<u8>)],
    out: &mut Vec<u8>,
) -> Result<(), Miss> {
    spans.sort_unstable_by_key(|(span, _)| span.start);
    let mut copied = 0;
    for (span, text) in spans.iter() {
        let before = bytes
            .get(copied..span.start)
            .filter(|_| span.start <= span.end && span.end <= bytes.len())
            .ok_or(Miss::Malformed)?;
        out.extend_from_slice(before);
        out.extend_from_slice(text);
        copied = span.end;
    }
    out.extend_from_slice(bytes.get(copied..).unwrap_or_default());
    Ok(())
}