mod compare;
pub mod enumeration;
mod fragment;
#[cfg(test)]
mod span_tests;
mod stream;
pub use compare::Equality;
pub use fragment::Fragment;
pub use stream::{StreamedBody, scan_body_children};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt;
use quick_xml::XmlVersion;
use quick_xml::events::{BytesDecl, BytesRef, BytesStart, Event};
use quick_xml::name::{QName, ResolveResult};
use quick_xml::reader::NsReader;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
pub max_depth: usize,
pub max_nodes: usize,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_depth: 256,
max_nodes: 4_000_000,
}
}
}
impl Limits {
#[must_use]
pub const fn mobile() -> Self {
Self {
max_depth: 128,
max_nodes: 500_000,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Syntax(String),
DocType,
TooDeep,
TooManyNodes,
NoRoot,
TooLarge,
NotUtf8(String),
NoSuchNode,
UndeclaredPrefix(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Syntax(message) => write!(f, "malformed XML: {message}"),
Self::DocType => f.write_str("XML with a DOCTYPE is not allowed"),
Self::TooDeep => f.write_str("XML nesting is too deep"),
Self::TooManyNodes => f.write_str("XML has too many nodes"),
Self::NoRoot => f.write_str("XML has no root element"),
Self::TooLarge => f.write_str("XML part is larger than 4 GiB"),
Self::NotUtf8(encoding) => write!(f, "XML part is in {encoding}, not in UTF-8"),
Self::NoSuchNode => f.write_str("XML document has no such node"),
Self::UndeclaredPrefix(prefix) => {
write!(
f,
"XML fragment uses the prefix {prefix} without a declaration"
)
}
}
}
}
impl std::error::Error for Error {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NodeId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NamespaceId(u32);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct StrSpan {
start: u32,
len: u32,
}
impl StrSpan {
const EMPTY: Self = Self { start: 0, len: 0 };
fn slice(self, buf: &str) -> &str {
let start = self.start as usize;
let end = start.saturating_add(self.len as usize);
buf.get(start..end).unwrap_or("")
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct SliceRange {
start: u32,
len: u32,
}
impl SliceRange {
const EMPTY: Self = Self { start: 0, len: 0 };
fn bounds(self) -> std::ops::Range<usize> {
let start = self.start as usize;
start..start.saturating_add(self.len as usize)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Name<'a> {
pub prefix: Option<&'a str>,
pub local: &'a str,
pub namespace: Option<NamespaceId>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Attribute<'a> {
pub name: Name<'a>,
pub value: &'a str,
}
#[derive(Clone, Copy, Debug)]
pub struct Attrs<'a> {
strings: &'a str,
attrs: &'a [ArenaAttr],
}
impl<'a> Attrs<'a> {
#[must_use]
pub const fn len(&self) -> usize {
self.attrs.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.attrs.is_empty()
}
#[must_use]
pub const fn iter(&self) -> AttrsIter<'a> {
AttrsIter {
strings: self.strings,
attrs: self.attrs,
}
}
#[must_use]
pub fn get(&self, index: usize) -> Option<Attribute<'a>> {
self.attrs.get(index).map(|attr| attr.view(self.strings))
}
}
#[derive(Clone, Debug)]
pub struct AttrsIter<'a> {
strings: &'a str,
attrs: &'a [ArenaAttr],
}
impl<'a> Iterator for AttrsIter<'a> {
type Item = Attribute<'a>;
fn next(&mut self) -> Option<Self::Item> {
let (first, rest) = self.attrs.split_first()?;
self.attrs = rest;
Some(first.view(self.strings))
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.attrs.len(), Some(self.attrs.len()))
}
}
impl DoubleEndedIterator for AttrsIter<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
let (last, rest) = self.attrs.split_last()?;
self.attrs = rest;
Some(last.view(self.strings))
}
}
impl ExactSizeIterator for AttrsIter<'_> {}
impl<'a> IntoIterator for Attrs<'a> {
type Item = Attribute<'a>;
type IntoIter = AttrsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &Attrs<'a> {
type Item = Attribute<'a>;
type IntoIter = AttrsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl PartialEq for Attrs<'_> {
fn eq(&self, other: &Self) -> bool {
self.len() == other.len() && self.iter().eq(other.iter())
}
}
impl Eq for Attrs<'_> {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Element<'a> {
pub name: Name<'a>,
pub attributes: Attrs<'a>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeKind<'a> {
Element(Element<'a>),
Text(&'a str),
Other(&'a str),
}
#[derive(Clone, Copy, Debug)]
struct ArenaAttr {
prefix: Option<StrSpan>,
local: StrSpan,
namespace: Option<NamespaceId>,
value: StrSpan,
}
impl ArenaAttr {
fn view<'a>(&self, strings: &'a str) -> Attribute<'a> {
Attribute {
name: Name {
prefix: self.prefix.map(|span| span.slice(strings)),
local: self.local.slice(strings),
namespace: self.namespace,
},
value: self.value.slice(strings),
}
}
}
#[derive(Clone, Copy, Debug)]
enum ArenaKind {
Element {
prefix: Option<StrSpan>,
local: StrSpan,
namespace: Option<NamespaceId>,
attrs: SliceRange,
},
Text(StrSpan),
Other(StrSpan),
}
#[derive(Clone, Copy, Debug)]
struct Node {
kind: ArenaKind,
children: SliceRange,
scope: Option<ScopeId>,
span: Span,
}
#[derive(Clone, Copy, Debug, Default)]
struct Span {
start: u32,
end: u32,
}
#[derive(Clone, Copy, Debug)]
struct ScopeId(u32);
#[derive(Clone, Debug)]
struct Scope {
outer: Option<ScopeId>,
bindings: Vec<(String, NamespaceId)>,
}
const UTF8_MARK: [u8; 3] = [0xEF, 0xBB, 0xBF];
const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
#[derive(Clone, Debug)]
pub struct Document {
nodes: Vec<Node>,
children_pool: Vec<NodeId>,
attrs: Vec<ArenaAttr>,
strings: String,
top: Vec<NodeId>,
namespaces: Vec<String>,
scopes: Vec<Scope>,
undeclared_prefixes: Vec<String>,
encoding: Option<String>,
}
impl Document {
pub fn parse(bytes: &[u8], limits: &Limits) -> Result<Self, Error> {
Builder::new(*limits, &[]).run(bytes)
}
pub fn parse_with_aliases(
bytes: &[u8],
limits: &Limits,
aliases: &[(&str, &str)],
) -> Result<Self, Error> {
Builder::new(*limits, aliases).run(bytes)
}
pub fn root(&self) -> Result<NodeId, Error> {
self.top
.iter()
.copied()
.find(|id| self.element(*id).is_some())
.ok_or(Error::NoRoot)
}
#[must_use]
pub fn kind(&self, id: NodeId) -> Option<NodeKind<'_>> {
let node = self.node(id)?;
Some(match node.kind {
ArenaKind::Element {
prefix,
local,
namespace,
attrs,
} => NodeKind::Element(Element {
name: Name {
prefix: prefix.map(|span| span.slice(&self.strings)),
local: local.slice(&self.strings),
namespace,
},
attributes: Attrs {
strings: &self.strings,
attrs: self.attrs.get(attrs.bounds()).unwrap_or(&[]),
},
}),
ArenaKind::Text(span) => NodeKind::Text(span.slice(&self.strings)),
ArenaKind::Other(span) => NodeKind::Other(span.slice(&self.strings)),
})
}
#[must_use]
pub fn element(&self, id: NodeId) -> Option<Element<'_>> {
match self.kind(id)? {
NodeKind::Element(element) => Some(element),
NodeKind::Text(_) | NodeKind::Other(_) => None,
}
}
#[must_use]
pub fn text(&self, id: NodeId) -> Option<&str> {
match self.node(id)?.kind {
ArenaKind::Text(span) => Some(span.slice(&self.strings)),
ArenaKind::Element { .. } | ArenaKind::Other(_) => None,
}
}
#[must_use]
pub fn children(&self, id: NodeId) -> &[NodeId] {
self.node(id)
.and_then(|node| self.children_pool.get(node.children.bounds()))
.unwrap_or(&[])
}
pub fn child_elements(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
self.children(id)
.iter()
.copied()
.filter(|child| self.element(*child).is_some())
}
pub fn set_children(&mut self, id: NodeId, children: Vec<NodeId>) {
if self.nodes.get(id.0 as usize).is_none() {
return;
}
let range = if children.is_empty() {
SliceRange::EMPTY
} else {
let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
let len = u32::try_from(children.len()).unwrap_or(u32::MAX);
self.children_pool.extend(children);
SliceRange { start, len }
};
if let Some(node) = self.nodes.get_mut(id.0 as usize) {
node.children = range;
}
}
pub fn set_attribute(&mut self, id: NodeId, namespace: Option<&str>, local: &str, value: &str) {
let namespace = namespace.map(|uri| {
let index = self.namespaces.iter().position(|known| known == uri);
NamespaceId(
u32::try_from(index.unwrap_or_else(|| {
self.namespaces.push(uri.to_owned());
self.namespaces.len() - 1
}))
.unwrap_or(u32::MAX),
)
});
let Some(ArenaKind::Element { attrs, .. }) =
self.nodes.get(id.0 as usize).map(|node| node.kind)
else {
return;
};
let bounds = attrs.bounds();
let existing_index = self.attrs.get(bounds.clone()).and_then(|slice| {
slice
.iter()
.position(|attr| {
attr.namespace == namespace && attr.local.slice(&self.strings) == local
})
.map(|offset| bounds.start + offset)
});
let value_span = push_str_arena(&mut self.strings, value);
if let Some(idx) = existing_index {
if let Some(attr) = self.attrs.get_mut(idx) {
attr.value = value_span;
}
return;
}
let local_span = push_str_arena(&mut self.strings, local);
let new_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
let old_len = bounds.len();
self.attrs.reserve(old_len + 1);
for idx in bounds {
if let Some(&copied) = self.attrs.get(idx) {
self.attrs.push(copied);
}
}
self.attrs.push(ArenaAttr {
prefix: None,
local: local_span,
namespace,
value: value_span,
});
let new_range = SliceRange {
start: new_start,
len: u32::try_from(old_len + 1).unwrap_or(u32::MAX),
};
if let Some(Node {
kind: ArenaKind::Element { attrs, .. },
..
}) = self.nodes.get_mut(id.0 as usize)
{
*attrs = new_range;
}
}
#[must_use]
pub fn undeclared_prefixes(&self) -> &[String] {
&self.undeclared_prefixes
}
#[must_use]
pub fn prefix_namespace(&self, id: NodeId, prefix: &str) -> Option<&str> {
self.element(id)?;
if prefix == "xml" {
return Some(XML_NAMESPACE);
}
let mut scope = self.node(id)?.scope;
while let Some(ScopeId(index)) = scope {
let found = self.scopes.get(index as usize)?;
if let Some((_, namespace)) = found.bindings.iter().find(|(name, _)| name == prefix) {
let uri = self.namespace_uri(*namespace);
return (!uri.is_empty()).then_some(uri);
}
scope = found.outer;
}
None
}
pub fn span(&self, id: NodeId) -> Result<std::ops::Range<usize>, Error> {
if let Some(encoding) = &self.encoding {
return Err(Error::NotUtf8(encoding.clone()));
}
let span = self.node(id).ok_or(Error::NoSuchNode)?.span;
Ok(span.start as usize..span.end as usize)
}
#[must_use]
pub fn namespaces_in_scope(&self, id: NodeId) -> Vec<(String, String)> {
let mut found: Vec<(String, String)> = Vec::new();
if self.element(id).is_none() {
return found;
}
let mut scope = self.node(id).and_then(|node| node.scope);
while let Some(ScopeId(index)) = scope {
let Some(outer) = self.scopes.get(index as usize) else {
break;
};
for (prefix, namespace) in &outer.bindings {
if found.iter().all(|(known, _)| known != prefix) {
found.push((prefix.clone(), self.namespace_uri(*namespace).to_owned()));
}
}
scope = outer.outer;
}
found
}
#[must_use]
pub fn namespace_uri(&self, id: NamespaceId) -> &str {
self.namespaces
.get(id.0 as usize)
.map_or("", String::as_str)
}
#[must_use]
pub fn is(&self, id: NodeId, namespace: &str, local: &str) -> bool {
self.element(id)
.is_some_and(|element| self.name_is(&element.name, Some(namespace), local))
}
#[must_use]
pub fn child(&self, id: NodeId, namespace: &str, local: &str) -> Option<NodeId> {
self.child_elements(id)
.find(|child| self.is(*child, namespace, local))
}
#[must_use]
pub fn attribute(&self, id: NodeId, namespace: Option<&str>, local: &str) -> Option<&str> {
self.element(id)?
.attributes
.iter()
.find(|attribute| self.name_is(&attribute.name, namespace, local))
.map(|attribute| attribute.value)
}
#[must_use]
pub fn text_content(&self, id: NodeId) -> String {
let mut out = String::new();
self.collect_text(id, &mut out);
out
}
fn collect_text(&self, id: NodeId, out: &mut String) {
if let Some(text) = self.text(id) {
out.push_str(text);
}
for child in self.children(id) {
self.collect_text(*child, out);
}
}
fn name_is(&self, name: &Name<'_>, namespace: Option<&str>, local: &str) -> bool {
let uri = name.namespace.map(|ns| self.namespace_uri(ns));
name.local == local && uri == namespace
}
fn node(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(id.0 as usize)
}
}
fn push_str_arena(strings: &mut String, text: &str) -> StrSpan {
if text.is_empty() {
return StrSpan::EMPTY;
}
let start = u32::try_from(strings.len()).unwrap_or(u32::MAX);
let len = u32::try_from(text.len()).unwrap_or(u32::MAX);
strings.push_str(text);
StrSpan { start, len }
}
struct Builder {
limits: Limits,
nodes: Vec<Node>,
children_pool: Vec<NodeId>,
pending_children: Vec<Vec<NodeId>>,
attrs: Vec<ArenaAttr>,
strings: String,
interned_names: HashMap<String, StrSpan>,
top: Vec<NodeId>,
stack: Vec<NodeId>,
scope_stack: Vec<Option<ScopeId>>,
scopes: Vec<Scope>,
namespaces: Vec<String>,
namespace_ids: HashMap<String, NamespaceId>,
aliases: HashMap<String, String>,
undeclared_prefixes: Vec<String>,
undeclared_seen: HashSet<String>,
offset: u64,
base_offset: u64,
skipped: u64,
encoding: Option<String>,
}
impl Builder {
fn new(limits: Limits, aliases: &[(&str, &str)]) -> Self {
Self {
limits,
nodes: Vec::new(),
children_pool: Vec::new(),
pending_children: Vec::new(),
attrs: Vec::new(),
strings: String::new(),
interned_names: HashMap::new(),
top: Vec::new(),
stack: Vec::new(),
scope_stack: Vec::new(),
scopes: Vec::new(),
namespaces: Vec::new(),
namespace_ids: HashMap::new(),
aliases: aliases
.iter()
.map(|(from, to)| ((*from).to_owned(), (*to).to_owned()))
.collect(),
undeclared_prefixes: Vec::new(),
undeclared_seen: HashSet::new(),
offset: 0,
base_offset: 0,
skipped: 0,
encoding: None,
}
}
fn intern_name(&mut self, name: &str) -> StrSpan {
if name.is_empty() {
return StrSpan::EMPTY;
}
if let Some(&span) = self.interned_names.get(name) {
return span;
}
let span = push_str_arena(&mut self.strings, name);
self.interned_names.insert(name.to_owned(), span);
span
}
fn run(mut self, bytes: &[u8]) -> Result<Document, Error> {
u32::try_from(
u64::try_from(bytes.len())
.unwrap_or(u64::MAX)
.saturating_add(self.base_offset),
)
.map_err(|_| Error::TooLarge)?;
if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
self.encoding = Some("UTF-16".to_owned());
}
if bytes.starts_with(&UTF8_MARK) {
self.skipped = UTF8_MARK.len() as u64;
}
let mut reader = NsReader::from_reader(bytes);
reader.config_mut().check_end_names = true;
let est_nodes = (bytes.len() / 64).min(self.limits.max_nodes);
self.nodes.reserve(est_nodes);
self.children_pool.reserve(est_nodes);
self.attrs.reserve(est_nodes);
self.strings.reserve(bytes.len() / 2);
let mut buf = Vec::new();
loop {
buf.clear();
let start = self.position(&reader)?;
let (resolved, event) = reader
.read_resolved_event_into(&mut buf)
.map_err(|error| Error::Syntax(error.to_string()))?;
let namespace = self.resolve(&resolved);
let span = Span {
start,
end: self.position(&reader)?,
};
match event {
Event::Eof => break,
Event::Start(tag) => {
let id = self.start_element(&reader, &tag, namespace, span)?;
self.open(id)?;
}
Event::Empty(tag) => {
self.start_element(&reader, &tag, namespace, span)?;
}
Event::End(_) => {
self.close(span.end);
}
other => self.leaf(other, span)?,
}
}
if self.stack.is_empty() {
Ok(Document {
nodes: self.nodes,
children_pool: self.children_pool,
attrs: self.attrs,
strings: self.strings,
top: self.top,
namespaces: self.namespaces,
scopes: self.scopes,
undeclared_prefixes: self.undeclared_prefixes,
encoding: self.encoding,
})
} else {
Err(Error::Syntax("unclosed element".to_owned()))
}
}
fn position(&self, reader: &NsReader<&[u8]>) -> Result<u32, Error> {
let position = (reader.buffer_position() + self.skipped)
.saturating_sub(self.offset)
.saturating_add(self.base_offset);
u32::try_from(position).map_err(|_| Error::TooLarge)
}
fn leaf(&mut self, event: Event<'_>, span: Span) -> Result<(), Error> {
match event {
Event::Text(text) => self.add_text(&text.xml10_content(), span),
Event::CData(data) => self.add_text(&data.into_inner(), span),
Event::GeneralRef(reference) => self.add_text(&resolve_reference(&reference)?, span),
Event::DocType(_) => Err(Error::DocType),
Event::Comment(comment) => {
let raw = comment.into_inner();
let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
self.strings.push_str("<!--");
self.strings.push_str(&raw);
self.strings.push_str("-->");
let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
self.add(ArenaKind::Other(StrSpan { start, len }), span)
.map(|_| ())
}
Event::Decl(declaration) => {
if self.encoding.is_none() {
self.encoding = declared_encoding(&declaration);
}
self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ())
}
Event::PI(_) => self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ()),
Event::Start(_) | Event::Empty(_) | Event::End(_) | Event::Eof => Ok(()),
}
}
fn resolve(&mut self, resolved: &ResolveResult<'_>) -> Option<NamespaceId> {
match resolved {
ResolveResult::Bound(namespace) => Some(self.intern(namespace.as_ref())),
ResolveResult::Unbound => None,
ResolveResult::Unknown(prefix) => {
if self.undeclared_seen.insert(prefix.clone()) {
self.undeclared_prefixes.push(prefix.clone());
}
None
}
}
}
fn intern(&mut self, uri: &str) -> NamespaceId {
let uri = self.aliases.get(uri).map_or(uri, String::as_str);
if let Some(id) = self.namespace_ids.get(uri) {
return *id;
}
let id = NamespaceId(u32::try_from(self.namespaces.len()).unwrap_or(u32::MAX));
let owned = uri.to_owned();
self.namespaces.push(owned.clone());
self.namespace_ids.insert(owned, id);
id
}
fn start_element(
&mut self,
reader: &NsReader<&[u8]>,
start: &BytesStart<'_>,
namespace: Option<NamespaceId>,
span: Span,
) -> Result<NodeId, Error> {
let (prefix, local) = self.split_name(start.name());
let attr_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
for attribute in start.attributes() {
let attribute = attribute.map_err(|error| Error::Syntax(error.to_string()))?;
let (resolved, _) = reader.resolver().resolve_attribute(attribute.key);
let attr_ns = self.resolve(&resolved);
let (attr_prefix, attr_local) = self.split_name(attribute.key);
let value = attribute
.normalized_value(XmlVersion::Implicit1_0)
.map_err(|error| Error::Syntax(error.to_string()))?;
let value_span = push_str_arena(&mut self.strings, &value);
self.attrs.push(ArenaAttr {
prefix: attr_prefix,
local: attr_local,
namespace: attr_ns,
value: value_span,
});
}
let attr_len = u32::try_from(self.attrs.len())
.unwrap_or(u32::MAX)
.saturating_sub(attr_start);
let attrs = SliceRange {
start: attr_start,
len: attr_len,
};
let scope = self.scope_of(attrs)?;
let id = self.add(
ArenaKind::Element {
prefix,
local,
namespace,
attrs,
},
span,
)?;
if let Some(node) = self.nodes.get_mut(id.0 as usize) {
node.scope = scope;
}
Ok(id)
}
fn split_name(&mut self, name: QName<'_>) -> (Option<StrSpan>, StrSpan) {
let local = self.intern_name(name.local_name().as_ref());
let prefix = name
.prefix()
.map(|prefix| self.intern_name(prefix.as_ref()));
(prefix, local)
}
fn scope_of(&mut self, attrs: SliceRange) -> Result<Option<ScopeId>, Error> {
let outer = self.scope_stack.last().copied().flatten();
let declared: Vec<(String, String)> = self
.attrs
.get(attrs.bounds())
.unwrap_or(&[])
.iter()
.filter_map(|attribute| {
let prefix_str = attribute.prefix.map(|span| span.slice(&self.strings));
let local_str = attribute.local.slice(&self.strings);
let binding_prefix = match prefix_str {
Some("xmlns") => local_str.to_owned(),
None if local_str == "xmlns" => String::new(),
_ => return None,
};
Some((
binding_prefix,
attribute.value.slice(&self.strings).to_owned(),
))
})
.collect();
if declared.is_empty() {
return Ok(outer);
}
let bindings = declared
.into_iter()
.map(|(prefix, uri)| (prefix, self.intern(&uri)))
.collect();
let id = ScopeId(u32::try_from(self.scopes.len()).map_err(|_| Error::TooManyNodes)?);
self.scopes.push(Scope { outer, bindings });
Ok(Some(id))
}
fn add_text(&mut self, text: &str, span: Span) -> Result<(), Error> {
let last = self.siblings().last().copied();
if let Some(last_id) = last
&& let Some(Node {
kind: ArenaKind::Text(prev_span),
..
}) = self.nodes.get(last_id.0 as usize).copied()
{
let prev_end = (prev_span.start as usize).saturating_add(prev_span.len as usize);
let new_span = if prev_end == self.strings.len() {
self.strings.push_str(text);
StrSpan {
start: prev_span.start,
len: prev_span
.len
.saturating_add(u32::try_from(text.len()).unwrap_or(u32::MAX)),
}
} else {
let prev_text = prev_span.slice(&self.strings).to_owned();
let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
self.strings.push_str(&prev_text);
self.strings.push_str(text);
let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
StrSpan { start, len }
};
if let Some(node) = self.nodes.get_mut(last_id.0 as usize) {
node.kind = ArenaKind::Text(new_span);
node.span.end = span.end;
}
return Ok(());
}
let text_span = push_str_arena(&mut self.strings, text);
self.add(ArenaKind::Text(text_span), span).map(|_| ())
}
fn siblings(&self) -> &[NodeId] {
let depth = self.stack.len();
if depth == 0 {
&self.top
} else {
self.pending_children
.get(depth - 1)
.map_or(&[], Vec::as_slice)
}
}
fn add(&mut self, kind: ArenaKind, span: Span) -> Result<NodeId, Error> {
if self.nodes.len() >= self.limits.max_nodes {
return Err(Error::TooManyNodes);
}
let id = NodeId(u32::try_from(self.nodes.len()).map_err(|_| Error::TooManyNodes)?);
self.nodes.push(Node {
kind,
children: SliceRange::EMPTY,
scope: None,
span,
});
let depth = self.stack.len();
if depth == 0 {
self.top.push(id);
} else if let Some(slot) = self.pending_children.get_mut(depth - 1) {
slot.push(id);
}
Ok(id)
}
fn open(&mut self, id: NodeId) -> Result<(), Error> {
if self.stack.len() >= self.limits.max_depth {
return Err(Error::TooDeep);
}
let depth = self.stack.len();
if depth == self.pending_children.len() {
self.pending_children.push(Vec::new());
} else if let Some(slot) = self.pending_children.get_mut(depth) {
slot.clear();
}
self.stack.push(id);
let scope = self.nodes.get(id.0 as usize).and_then(|node| node.scope);
self.scope_stack.push(scope);
Ok(())
}
fn close(&mut self, end: u32) {
let Some(parent_id) = self.stack.pop() else {
return;
};
let depth = self.stack.len();
let range = if let Some(slot) = self.pending_children.get_mut(depth) {
if slot.is_empty() {
SliceRange::EMPTY
} else {
let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
let len = u32::try_from(slot.len()).unwrap_or(u32::MAX);
self.children_pool.extend_from_slice(slot);
slot.clear();
SliceRange { start, len }
}
} else {
SliceRange::EMPTY
};
if let Some(node) = self.nodes.get_mut(parent_id.0 as usize) {
node.span.end = end;
node.children = range;
}
self.scope_stack.pop();
}
}
fn declared_encoding(declaration: &BytesDecl<'_>) -> Option<String> {
let name = declaration.encoding()?.ok()?;
let utf8 = name.eq_ignore_ascii_case("utf-8") || name.eq_ignore_ascii_case("utf8");
(!utf8).then(|| name.into_owned())
}
fn resolve_reference(reference: &BytesRef<'_>) -> Result<Cow<'static, str>, Error> {
if let Some(ch) = reference
.resolve_char_ref()
.map_err(|error| Error::Syntax(error.to_string()))?
{
return Ok(Cow::Owned(ch.to_string()));
}
let name: &str = reference.as_ref();
let text = match name {
"lt" => "<",
"gt" => ">",
"amp" => "&",
"apos" => "'",
"quot" => "\"",
other => return Err(Error::Syntax(format!("unknown entity &{other};"))),
};
Ok(Cow::Borrowed(text))
}
#[cfg(test)]
mod tests {
use super::{Document, Error, Limits, NodeKind};
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
fn parse(xml: &str) -> Result<Document, Error> {
Document::parse(xml.as_bytes(), &Limits::default())
}
#[test]
fn reads_elements_attributes_and_text() {
let doc = parse(&format!(
r#"<?xml version="1.0"?><w:document xmlns:w="{W}"><w:p><w:r><w:t xml:space="preserve"> a & b A</w:t></w:r><w:jc w:val="both"/></w:p></w:document>"#
))
.unwrap();
let root = doc.root().unwrap();
assert!(doc.is(root, W, "document"));
let p = doc.child(root, W, "p").unwrap();
let t = doc.child(doc.child(p, W, "r").unwrap(), W, "t").unwrap();
assert_eq!(doc.text_content(t), " a & b A");
let jc = doc.child(p, W, "jc").unwrap();
assert_eq!(doc.attribute(jc, Some(W), "val"), Some("both"));
assert_eq!(doc.attribute(jc, None, "val"), None);
let element = doc.element(jc).unwrap();
assert_eq!(element.name.prefix, Some("w"));
assert_eq!(doc.namespace_uri(element.name.namespace.unwrap()), W);
}
#[test]
fn sets_the_children_of_a_node() {
let mut doc = parse("<a><b>x</b><c/><d/></a>").unwrap();
let root = doc.root().unwrap();
let [b, c, d] = [0, 1, 2].map(|i| doc.children(root)[i]);
let x = doc.children(b)[0];
doc.set_children(root, vec![d, x, b]);
doc.set_children(b, Vec::new());
assert_eq!(doc.children(root), [d, x, b]);
assert_eq!(doc.text_content(root), "x");
assert_eq!(doc.children(c), []);
let mut other = parse("<a/>").unwrap();
other.set_children(d, vec![d]);
assert_eq!(other.children(d), []);
}
#[test]
fn sets_an_attribute_of_an_element() {
let mut doc = parse(&format!(r#"<w:r xmlns:w="{W}" w:rsidR="00AB">x</w:r>"#)).unwrap();
let root = doc.root().unwrap();
doc.set_attribute(root, Some("urn:note"), "change", "3");
doc.set_attribute(root, Some(W), "rsidR", "00CD");
doc.set_attribute(root, Some("urn:note"), "change", "4");
assert_eq!(doc.attribute(root, Some("urn:note"), "change"), Some("4"));
assert_eq!(doc.attribute(root, Some(W), "rsidR"), Some("00CD"));
let text = doc.children(root)[0];
doc.set_attribute(text, None, "a", "b");
assert_eq!(doc.attribute(text, None, "a"), None);
}
#[test]
fn keeps_unprefixed_attributes_and_comments() {
let doc = parse(r#"<Relationships><!-- note --><Relationship Id="rId1" Target="a.xml"/></Relationships>"#).unwrap();
let root = doc.root().unwrap();
let rel = doc.child_elements(root).next().unwrap();
assert_eq!(doc.attribute(rel, None, "Id"), Some("rId1"));
let comment = doc.children(root)[0];
assert_eq!(doc.kind(comment), Some(NodeKind::Other("<!-- note -->")));
assert!(doc.text(comment).is_none());
assert!(doc.element(comment).is_none());
}
#[test]
fn joins_text_around_references_and_cdata() {
let doc = parse("<a>x<y<![CDATA[<z>]]>>'"</a>").unwrap();
let root = doc.root().unwrap();
assert_eq!(doc.children(root).len(), 1);
assert_eq!(doc.text_content(root), "x<y<z>>'\"");
}
#[test]
fn refuses_doctype_and_unknown_entities() {
assert_eq!(parse("<!DOCTYPE a><a/>").unwrap_err(), Error::DocType);
assert!(matches!(parse("<a>&bogus;</a>"), Err(Error::Syntax(_))));
assert_eq!(
parse("<!-- only -->").unwrap().root().unwrap_err(),
Error::NoRoot
);
}
#[test]
fn refuses_bad_nesting() {
assert!(matches!(parse("<a><b></a>"), Err(Error::Syntax(_))));
assert!(matches!(parse("<a>"), Err(Error::Syntax(_))));
}
fn undeclared() -> Document {
parse(&format!(
r#"<w:document xmlns:w="{W}" xml:space="preserve"><p:a q:b="1" w:c="2"/><p:d></p:d><w:e p:f="3"/></w:document>"#
))
.unwrap()
}
#[test]
fn lists_each_undeclared_prefix_once_and_gives_its_elements_no_namespace() {
let doc = undeclared();
assert_eq!(doc.undeclared_prefixes(), ["p", "q"]);
let root = doc.root().unwrap();
let [a, _, e] = [0, 1, 2].map(|i| doc.children(root)[i]);
let element = doc.element(a).unwrap();
assert_eq!(element.name.prefix, Some("p"));
assert_eq!(element.name.namespace, None);
assert!(doc.is(e, W, "e"));
let declared = parse(&format!(r#"<w:a xmlns:w="{W}" xml:space="preserve"/>"#)).unwrap();
assert_eq!(declared.undeclared_prefixes(), [] as [&str; 0]);
}
#[test]
fn reads_an_attribute_of_an_undeclared_prefix_as_one_without_a_prefix() {
let doc = undeclared();
let root = doc.root().unwrap();
let [a, e] = [0, 2].map(|i| doc.children(root)[i]);
assert_eq!(doc.attribute(a, None, "b"), Some("1"));
assert_eq!(doc.attribute(a, Some(W), "c"), Some("2"));
assert_eq!(doc.attribute(e, None, "f"), Some("3"));
}
#[test]
fn resolves_namespace_aliases() {
let xml = r#"<s:document xmlns:s="urn:strict"><s:body s:val="1"/></s:document>"#;
let doc =
Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
.unwrap();
let root = doc.root().unwrap();
assert!(doc.is(root, W, "document"));
let body = doc.child(root, W, "body").unwrap();
assert_eq!(doc.attribute(body, Some(W), "val"), Some("1"));
let plain = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
assert!(!plain.is(plain.root().unwrap(), W, "document"));
}
#[test]
fn binds_a_prefix_by_the_nearest_declaration_in_scope() {
let doc = parse(concat!(
r#"<a xmlns:p="urn:outer" xmlns="urn:default">"#,
r#"<b xmlns:p="urn:inner" xmlns:q="urn:q"><c/></b><d/><e xmlns=""/>t</a>"#,
))
.unwrap();
let root = doc.root().unwrap();
let [b, d, e, text] = [0, 1, 2, 3].map(|i| doc.children(root)[i]);
let c = doc.children(b)[0];
let cases = [
(root, "p", Some("urn:outer")),
(c, "p", Some("urn:inner")),
(c, "q", Some("urn:q")),
(d, "p", Some("urn:outer")),
(d, "q", None),
(c, "", Some("urn:default")),
(e, "", None),
(e, "xml", Some(super::XML_NAMESPACE)),
(text, "p", None),
(text, "xml", None),
];
for (node, prefix, namespace) in cases {
assert_eq!(
doc.prefix_namespace(node, prefix),
namespace,
"{node:?} {prefix}"
);
}
}
#[test]
fn binds_a_prefix_to_its_alias() {
let xml = r#"<a xmlns:s="urn:strict"><b/></a>"#;
let doc =
Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
.unwrap();
let b = doc.children(doc.root().unwrap())[0];
assert_eq!(doc.prefix_namespace(b, "s"), Some(W));
}
#[test]
fn enforces_limits() {
let deep = Limits {
max_depth: 2,
max_nodes: 100,
};
assert_eq!(
Document::parse(b"<a><b><c/></b></a>", &deep).map(|_| ()),
Ok(())
);
assert_eq!(
Document::parse(b"<a><b><c></c></b></a>", &deep).unwrap_err(),
Error::TooDeep
);
let few = Limits {
max_depth: 10,
max_nodes: 2,
};
assert_eq!(
Document::parse(b"<a><b/><c/></a>", &few).unwrap_err(),
Error::TooManyNodes
);
}
#[test]
fn errors_display() {
for error in [
Error::Syntax("x".into()),
Error::DocType,
Error::TooDeep,
Error::TooManyNodes,
Error::NoRoot,
] {
assert_ne!(error.to_string(), "");
}
}
}