use alloc::{string::String, vec::Vec};
pub mod lenient;
pub mod reader;
pub use lenient::{Lenient, Token};
pub use reader::{Attr, Event, ReadError, Reader, Start, NS_XML, NS_XMLNS};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Name {
pub ns: String,
pub local: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Node {
pub name: Name,
pub attrs: Vec<(Name, String)>,
pub text: String,
pub children: Vec<Node>,
}
impl Node {
pub fn is(&self, ns: &str, local: &str) -> bool {
self.name.ns == ns && self.name.local == local
}
pub fn attr(&self, ns: &str, local: &str) -> Option<&str> {
self.attrs
.iter()
.find(|(n, _)| n.ns == ns && n.local == local)
.map(|(_, v)| v.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Syntax,
Limit,
Unsupported,
Depth,
Attributes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
pub bytes: usize,
pub nodes: usize,
pub depth: usize,
}
impl Default for Limits {
fn default() -> Self {
Self { bytes: 4 * 1024 * 1024, nodes: 30000, depth: 48 }
}
}
pub fn valid_char(c: char) -> bool {
matches!(c as u32, 9 | 10 | 13 | 0x20..=0xd7ff | 0xe000..=0xfffd | 0x10000..=0x10ffff)
}
pub fn escape(s: &str) -> Result<String, Error> {
let mut out = String::new();
for c in s.chars() {
if !valid_char(c) {
return Err(Error::Syntax);
}
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
'\r' => out.push_str(" "),
'\n' => out.push_str(" "),
'\t' => out.push_str("	"),
_ => out.push(c),
}
}
Ok(out)
}
pub fn parse(s: &str) -> Result<Node, Error> {
parse_with(s, Limits::default())
}
const SCOPE_BYTES: usize = 4096;
const TREE_ATTRS: usize = 64;
pub fn parse_with(s: &str, lim: Limits) -> Result<Node, Error> {
if s.len() > lim.bytes {
return Err(Error::Limit);
}
let mut r = Reader::new(s, lim.depth.saturating_add(1), TREE_ATTRS);
let mut stack: Vec<(Node, usize)> = Vec::new();
let (mut nodes, mut kept, mut scope) = (0usize, 0usize, 0usize);
let kept_max = lim.bytes.saturating_mul(16);
let mut root = None;
loop {
let ev = r.next().map_err(|e| match e.error {
Error::Depth | Error::Attributes => Error::Limit,
e => e,
})?;
match ev {
Event::Start(st) => {
nodes += 1;
if nodes > lim.nodes {
return Err(Error::Limit);
}
let own: usize = st.attrs.iter().filter(|a| a.ns == NS_XMLNS).map(|a| a.local.len() + a.value.len()).sum();
scope += own;
if scope > SCOPE_BYTES {
return Err(Error::Limit);
}
let name = Name { ns: String::from(&*st.ns), local: String::from(st.local) };
kept = kept.saturating_add(name.ns.len() + name.local.len());
let mut attrs = Vec::with_capacity(st.attrs.len());
for a in st.attrs.iter().filter(|a| a.ns != NS_XMLNS) {
kept = kept.saturating_add(a.ns.len() + a.local.len());
attrs.push((Name { ns: String::from(&*a.ns), local: String::from(a.local) }, String::from(&*a.value)));
}
if kept > kept_max {
return Err(Error::Limit);
}
stack.push((Node { name, attrs, text: String::new(), children: Vec::new() }, own));
}
Event::End { .. } => {
let Some((mut node, own)) = stack.pop() else { return Err(Error::Syntax) };
scope -= own;
if !node.children.is_empty() {
if !node.text.trim_matches([' ', '\t', '\r', '\n']).is_empty() {
return Err(Error::Unsupported);
}
node.text.clear();
}
match stack.last_mut() {
Some((parent, _)) => parent.children.push(node),
None => root = Some(node),
}
}
Event::Text(t) => {
if let Some((node, _)) = stack.last_mut() {
node.text.push_str(&t);
}
}
Event::CData(_) | Event::Comment(_) | Event::Pi { .. } => return Err(Error::Unsupported),
Event::Eof => return root.ok_or(Error::Syntax),
}
}
}