grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/xml/tree.rs
// Purpose:   One XML record as a small tree, written as JSON in one pass
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A record's elements held as owned strings until the record closes. The tree
//! is needed because `<a/><b/><a/>` must group both `a` under one key.

use std::collections::HashMap;

use super::{Arrays, XmlConfig};

#[derive(Debug, Default)]
struct Node {
    /// The name as the namespace mode writes it.
    name: String,
    /// The local name, for `single` paths.
    local: String,
    attrs: Vec<(String, String)>,
    children: Vec<usize>,
    text: String,
}

/// Where a record sits in its document.
pub(super) struct Meta<'a> {
    pub element: &'a str,
    pub path: &'a str,
    pub index: usize,
    /// The record element's slash path of local names.
    pub local_path: &'a str,
    /// `_xml.context`, rendered, when carry copied anything.
    pub context: Option<&'a [u8]>,
    /// `_xml.soap`, rendered, inside a SOAP envelope.
    pub soap: Option<&'a [u8]>,
}

/// One record being read.
#[derive(Debug, Default)]
pub(super) struct Record {
    nodes: Vec<Node>,
    open: Vec<usize>,
}

impl Record {
    /// Open an element inside the record, or the record element itself.
    pub fn open(&mut self, name: String, local: String, attrs: Vec<(String, String)>) {
        let id = self.nodes.len();
        self.nodes.push(Node {
            name,
            local,
            attrs,
            ..Node::default()
        });
        if let Some(&parent) = self.open.last() {
            self.nodes[parent].children.push(id);
        }
        self.open.push(id);
    }

    /// Text, CDATA or a resolved reference inside the innermost open element.
    pub fn text(&mut self, s: &str) {
        if let Some(&top) = self.open.last() {
            self.nodes[top].text.push_str(s);
        }
    }

    /// Close the innermost element. `true` when that closes the record.
    pub fn close(&mut self) -> bool {
        self.open.pop();
        self.open.is_empty()
    }

    /// The record as one JSON object.
    pub fn write(&self, cfg: &XmlConfig, meta: &Meta<'_>, out: &mut Vec<u8>) {
        let mut path = meta.local_path.to_owned();
        self.object(0, cfg, &mut path, Some(meta), out);
    }

    /// The node at `path` of local names below the root, first match each step.
    fn find(&self, path: &[&str]) -> Option<usize> {
        let mut id = 0;
        for step in path {
            id = *self.nodes[id]
                .children
                .iter()
                .find(|&&c| self.nodes[c].local == *step)?;
        }
        Some(id)
    }

    /// The trimmed text at `path`, `None` when no such element.
    pub fn text_at(&self, path: &[&str]) -> Option<String> {
        self.find(path)
            .map(|id| trim(&self.nodes[id].text).to_owned())
    }

    /// The value at `path` as JSON, `None` when no such element.
    pub fn value_at(&self, cfg: &XmlConfig, path: &[&str]) -> Option<Vec<u8>> {
        let id = self.find(path)?;
        let mut out = Vec::new();
        let mut local = String::new();
        self.value(id, cfg, &mut local, &mut out);
        Some(out)
    }

    /// The element as a value, not a record: a string or an object.
    pub fn write_value(&self, cfg: &XmlConfig, local_path: &str, out: &mut Vec<u8>) {
        let mut path = local_path.to_owned();
        self.value(0, cfg, &mut path, out);
    }

    fn value(&self, id: usize, cfg: &XmlConfig, path: &mut String, out: &mut Vec<u8>) {
        let node = &self.nodes[id];
        if node.attrs.is_empty() && node.children.is_empty() {
            string(out, trim(&node.text));
        } else {
            self.object(id, cfg, path, None, out);
        }
    }

    fn object(
        &self,
        id: usize,
        cfg: &XmlConfig,
        path: &mut String,
        meta: Option<&Meta<'_>>,
        out: &mut Vec<u8>,
    ) {
        let node = &self.nodes[id];
        out.push(b'{');
        let mut first = true;
        let mut key = |out: &mut Vec<u8>, parts: &[&str]| {
            if !first {
                out.push(b',');
            }
            first = false;
            string(out, &parts.concat());
            out.push(b':');
        };
        for (name, value) in &node.attrs {
            key(out, &[&cfg.attr_prefix, name]);
            string(out, value);
        }
        for (name, ids) in groups(&self.nodes, &node.children) {
            let len = path.len();
            path.push('/');
            path.push_str(&self.nodes[ids[0]].local);
            key(out, &[name]);
            let as_array = match cfg.arrays {
                Arrays::Always => ids.len() > 1 || !cfg.single.iter().any(|s| s == path),
                Arrays::Auto => ids.len() > 1,
            };
            if as_array {
                out.push(b'[');
                for (i, &child) in ids.iter().enumerate() {
                    if i > 0 {
                        out.push(b',');
                    }
                    self.value(child, cfg, path, out);
                }
                out.push(b']');
            } else {
                self.value(ids[0], cfg, path, out);
            }
            path.truncate(len);
        }
        let text = trim(&node.text);
        if !text.is_empty() {
            key(out, &[&cfg.text_key]);
            string(out, text);
        }
        if let (Some(meta), Some(name)) = (meta, cfg.meta_key.as_deref()) {
            key(out, &[name]);
            out.extend_from_slice(b"{\"element\":");
            string(out, meta.element);
            out.extend_from_slice(b",\"path\":");
            string(out, meta.path);
            out.extend_from_slice(b",\"index\":");
            out.extend_from_slice(meta.index.to_string().as_bytes());
            if let Some(context) = meta.context {
                out.extend_from_slice(b",\"context\":");
                out.extend_from_slice(context);
            }
            if let Some(soap) = meta.soap {
                out.extend_from_slice(b",\"soap\":");
                out.extend_from_slice(soap);
            }
            out.push(b'}');
        }
        out.push(b'}');
    }
}

/// Children grouped by name, names in order of first occurrence.
fn groups<'n>(nodes: &'n [Node], children: &[usize]) -> Vec<(&'n str, Vec<usize>)> {
    let mut order: Vec<(&str, Vec<usize>)> = Vec::new();
    let mut index: HashMap<&str, usize> = HashMap::new();
    for &c in children {
        let name = nodes[c].name.as_str();
        let slot = *index.entry(name).or_insert_with(|| {
            order.push((name, Vec::new()));
            order.len() - 1
        });
        order[slot].1.push(c);
    }
    order
}

/// `s` without XML white space at either end.
fn trim(s: &str) -> &str {
    s.trim_matches(|c| matches!(c, ' ' | '\t' | '\r' | '\n'))
}

/// `s` as a JSON string.
pub(super) fn string(out: &mut Vec<u8>, s: &str) {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    out.push(b'"');
    for &b in s.as_bytes() {
        match b {
            b'"' => out.extend_from_slice(b"\\\""),
            b'\\' => out.extend_from_slice(b"\\\\"),
            b'\n' => out.extend_from_slice(b"\\n"),
            b'\r' => out.extend_from_slice(b"\\r"),
            b'\t' => out.extend_from_slice(b"\\t"),
            0..=0x1f => {
                out.extend_from_slice(b"\\u00");
                out.push(HEX[usize::from(b >> 4)]);
                out.push(HEX[usize::from(b & 0x0f)]);
            }
            _ => out.push(b),
        }
    }
    out.push(b'"');
}