use std::collections::HashMap;
use super::{Arrays, XmlConfig};
#[derive(Debug, Default)]
struct Node {
name: String,
local: String,
attrs: Vec<(String, String)>,
children: Vec<usize>,
text: String,
}
pub(super) struct Meta<'a> {
pub element: &'a str,
pub path: &'a str,
pub index: usize,
pub local_path: &'a str,
pub context: Option<&'a [u8]>,
pub soap: Option<&'a [u8]>,
}
#[derive(Debug, Default)]
pub(super) struct Record {
nodes: Vec<Node>,
open: Vec<usize>,
}
impl Record {
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);
}
pub fn text(&mut self, s: &str) {
if let Some(&top) = self.open.last() {
self.nodes[top].text.push_str(s);
}
}
pub fn close(&mut self) -> bool {
self.open.pop();
self.open.is_empty()
}
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);
}
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)
}
pub fn text_at(&self, path: &[&str]) -> Option<String> {
self.find(path)
.map(|id| trim(&self.nodes[id].text).to_owned())
}
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)
}
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'}');
}
}
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
}
fn trim(s: &str) -> &str {
s.trim_matches(|c| matches!(c, ' ' | '\t' | '\r' | '\n'))
}
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'"');
}