grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/tree.rs
// Purpose:   The field writer the tree-shaped formats share
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Writes a document of maps, lists and scalars as `ndjson` writes a JSON
//! record: a nested key joins its parents with `.`, a list writes each element
//! under its own key, and a key holding `.`, `[`, `]` or `"` is quoted.
//!
//! It holds the bounds `ndjson` holds: 64 containers deep, the root counted,
//! and the name bytes a record writes. A document that fails anywhere leaves
//! the sink as it was.

use std::borrow::Cow;

use crate::parse::{FieldSink, FieldValue, ParseError, SinkMark};
use crate::path::key_part;

/// Containers a document may nest, the root counted as the first.
pub const MAX_DEPTH: usize = 64;

/// Name bytes a document may write, as a multiple of its own size.
const NAME_FACTOR: usize = 16;

/// Name bytes any document may write, whatever its size.
const NAME_FLOOR: usize = 1 << 20;

/// One open container.
#[derive(Debug)]
enum Open {
    /// A map, the key its next value goes under once that key is read, and
    /// the bytes of the prefix it pushed, if it pushed one.
    Map {
        key: Option<String>,
        pushed: Option<usize>,
    },
    /// A list, whose elements go under `key`, or under no name at the root.
    List { key: Option<String> },
}

/// A document's walk into a sink.
pub struct Tree<'s, 'a> {
    out: &'s mut dyn FieldSink<'a>,
    mark: SinkMark,
    open: Vec<Open>,
    /// Bytes of the prefixes this walk has pushed.
    prefix: usize,
    names: usize,
    budget: usize,
}

impl<'s, 'a> Tree<'s, 'a> {
    /// A walk into `out` for a document of `len` bytes.
    pub fn new(out: &'s mut dyn FieldSink<'a>, len: usize) -> Self {
        let mark = out.mark();
        Self {
            out,
            mark,
            open: Vec::new(),
            prefix: 0,
            names: 0,
            budget: NAME_FLOOR.max(len.saturating_mul(NAME_FACTOR)),
        }
    }

    /// The next value's key, in the map that is open.
    pub fn key(&mut self, key: Cow<'_, str>) {
        if let Some(Open::Map { key: slot, .. }) = self.open.last_mut() {
            *slot = Some(key_part(key).into_owned());
        }
    }

    /// The name part the next value goes under, taken from its map.
    fn take_name(&mut self) -> Option<String> {
        match self.open.last_mut() {
            Some(Open::Map { key, .. }) => key.take(),
            Some(Open::List { key }) => key.clone(),
            None => None,
        }
    }

    /// Write `value` as the next value.
    ///
    /// # Errors
    ///
    /// [`ParseError::Limit`] past the name budget.
    pub fn scalar(&mut self, value: FieldValue<'a>) -> Result<(), ParseError> {
        let Some(name) = self.take_name() else {
            return Ok(());
        };
        self.names += self.prefix + name.len();
        if self.names > self.budget {
            return Err(ParseError::Limit {
                what: "field names longer in total than the document allows",
            });
        }
        self.out.field(&name, value);
        Ok(())
    }

    /// Skip the next value, such as a null.
    #[cfg(any(feature = "parse-yaml", feature = "parse-msgpack"))]
    pub fn skip(&mut self) {
        self.take_name();
    }

    const fn deeper(&self) -> Result<(), ParseError> {
        if self.open.len() >= MAX_DEPTH {
            return Err(ParseError::Limit {
                what: "a document nested deeper than 64 levels",
            });
        }
        Ok(())
    }

    /// Open a map as the next value.
    ///
    /// # Errors
    ///
    /// [`ParseError::Limit`] past [`MAX_DEPTH`].
    pub fn open_map(&mut self) -> Result<(), ParseError> {
        self.deeper()?;
        let pushed = self.take_name().map(|name| {
            self.out.push_prefix(&name);
            self.out.push_prefix(".");
            self.prefix += name.len() + 1;
            name.len() + 1
        });
        self.open.push(Open::Map { key: None, pushed });
        Ok(())
    }

    /// Open a list as the next value. At the root its elements have no name
    /// and write nothing.
    ///
    /// # Errors
    ///
    /// [`ParseError::Limit`] past [`MAX_DEPTH`].
    pub fn open_list(&mut self) -> Result<(), ParseError> {
        self.deeper()?;
        let key = self.take_name();
        self.open.push(Open::List { key });
        Ok(())
    }

    /// Close the container opened last.
    pub fn close(&mut self) {
        if let Some(Open::Map {
            pushed: Some(len), ..
        }) = self.open.pop()
        {
            self.out.pop_prefix();
            self.out.pop_prefix();
            self.prefix -= len;
        }
    }

    /// The walk's outcome: on an error every prefix it pushed is popped and
    /// the sink rolled back.
    ///
    /// # Errors
    ///
    /// `result`'s error.
    pub fn finish(mut self, result: Result<(), ParseError>) -> Result<(), ParseError> {
        while let Some(open) = self.open.pop() {
            if let Open::Map {
                pushed: Some(_), ..
            } = open
            {
                self.out.pop_prefix();
                self.out.pop_prefix();
            }
        }
        if result.is_err() {
            self.out.rollback(self.mark);
        }
        result
    }
}