use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::str::FromStr;
use memchr::{memchr, memchr2, memchr3, memmem};
use thiserror::Error;
const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Path {
steps: Vec<Step>,
attribute: Option<Name>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Name {
local: Box<str>,
namespace: Option<Box<str>>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Select {
Nth(usize),
Attribute(Name, Box<str>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Step {
name: Name,
select: Select,
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PathError {
#[error("a path needs at least one element")]
Empty,
#[error("{why} at byte {at}")]
Syntax {
at: usize,
why: &'static str,
},
#[error("the prefix {prefix:?} has no namespace bound to it")]
UnboundPrefix {
prefix: String,
},
}
impl Path {
pub fn parse(text: &str) -> Result<Self, PathError> {
Self::parse_with(text, &[])
}
pub fn parse_with(text: &str, prefixes: &[(&str, &str)]) -> Result<Self, PathError> {
if text.is_empty() {
return Err(PathError::Empty);
}
let mut reader = PathReader {
text,
at: 0,
prefixes,
};
let mut steps = Vec::new();
loop {
let name = reader.name()?;
let select = if reader.eat(b'[') {
reader.select()?
} else {
Select::Nth(0)
};
steps.push(Step { name, select });
match reader.peek() {
None => {
return Ok(Self {
steps,
attribute: None,
});
}
Some(b'.') => reader.at += 1,
Some(b'@') => {
reader.at += 1;
let attribute = Some(reader.name()?);
if reader.peek().is_some() {
return Err(syntax(reader.at, "the end of the path after an attribute"));
}
return Ok(Self { steps, attribute });
}
Some(_) => return Err(syntax(reader.at, "`.`, `[` or `@` after a name")),
}
}
}
}
impl FromStr for Path {
type Err = PathError;
fn from_str(text: &str) -> Result<Self, PathError> {
Self::parse(text)
}
}
const fn syntax(at: usize, why: &'static str) -> PathError {
PathError::Syntax { at, why }
}
struct PathReader<'t, 'p> {
text: &'t str,
at: usize,
prefixes: &'p [(&'p str, &'p str)],
}
impl<'t> PathReader<'t, '_> {
fn peek(&self) -> Option<u8> {
self.text.as_bytes().get(self.at).copied()
}
fn eat(&mut self, byte: u8) -> bool {
let hit = self.peek() == Some(byte);
self.at += usize::from(hit);
hit
}
fn run(&mut self) -> &'t str {
let start = self.at;
let len = self.text.as_bytes()[start..]
.iter()
.position(|&b| !path_name_byte(b))
.unwrap_or(self.text.len() - start);
self.at += len;
&self.text[start..start + len]
}
fn name(&mut self) -> Result<Name, PathError> {
let first = self.run().to_owned();
if first.is_empty() {
return Err(syntax(self.at, "a name"));
}
if !self.eat(b':') {
return Ok(Name {
local: first.into_boxed_str(),
namespace: None,
});
}
let local = self.run();
if local.is_empty() {
return Err(syntax(self.at, "a local name after `:`"));
}
let namespace = if first == "xml" {
XML_NAMESPACE
} else {
self.prefixes
.iter()
.find(|(prefix, _)| *prefix == first)
.map(|(_, uri)| *uri)
.ok_or(PathError::UnboundPrefix { prefix: first })?
};
Ok(Name {
local: local.into(),
namespace: Some(namespace.into()),
})
}
fn select(&mut self) -> Result<Select, PathError> {
let select = if self.eat(b'@') {
let name = self.name()?;
if !self.eat(b'=') {
return Err(syntax(self.at, "`=` after the attribute"));
}
let quote = self
.peek()
.filter(|&b| b == b'"' || b == b'\'')
.ok_or_else(|| syntax(self.at, "a quoted value"))?;
let from = self.at + 1;
let len = memchr(quote, &self.text.as_bytes()[from..])
.ok_or_else(|| syntax(self.at, "a closing quote"))?;
self.at = from + len + 1;
Select::Attribute(name, self.text[from..from + len].into())
} else {
let from = self.at;
let digits = self.text.as_bytes()[from..]
.iter()
.take_while(|b| b.is_ascii_digit())
.count();
let text = &self.text[from..from + digits];
if text.len() > 1 && text.starts_with('0') {
return Err(syntax(from, "an index with no leading zero"));
}
let index = text
.parse::<usize>()
.map_err(|_| syntax(from, "an index or `@`"))?;
self.at += digits;
Select::Nth(index)
};
if !self.eat(b']') {
return Err(syntax(self.at, "`]`"));
}
Ok(select)
}
}
const fn path_name_byte(b: u8) -> bool {
!matches!(
b,
b'.' | b'[' | b']' | b'@' | b'=' | b':' | b'"' | b'\'' | b' ' | b'\t' | b'\n' | b'\r'
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
Text,
Element,
Empty,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Source {
Content,
Attribute,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Raw<'a> {
text: &'a str,
kind: Kind,
start: usize,
source: Source,
}
impl<'a> Raw<'a> {
#[must_use]
pub const fn span(self) -> Range<usize> {
self.start..self.start + self.text.len()
}
#[must_use]
pub const fn text(self) -> &'a str {
self.text
}
#[must_use]
pub const fn kind(self) -> Kind {
self.kind
}
#[must_use]
pub const fn is_attribute(self) -> bool {
matches!(self.source, Source::Attribute)
}
#[must_use]
pub fn to_str(self) -> Option<Cow<'a, str>> {
let bytes = self.text.as_bytes();
let plain = match self.source {
Source::Content if self.kind == Kind::Element => return None,
Source::Content => memchr3(b'&', b'<', b'\r', bytes).is_none(),
Source::Attribute => !bytes.iter().any(|&b| attribute_special(b)),
};
if plain {
return Some(Cow::Borrowed(self.text));
}
let mut out = Vec::with_capacity(bytes.len());
let decoded = match self.source {
Source::Content => decode_text(bytes, |part| out.extend_from_slice(part)),
Source::Attribute => decode_attribute(bytes, |part| out.extend_from_slice(part)),
};
decoded.ok()?;
String::from_utf8(out).ok().map(Cow::Owned)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Slot<'a> {
Found(Raw<'a>),
MissingRoot,
MissingField(usize),
WrongParentType(usize),
Malformed,
}
impl<'a> Slot<'a> {
#[must_use]
pub const fn found(self) -> Option<Raw<'a>> {
match self {
Self::Found(raw) => Some(raw),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Paths {
nodes: Vec<Node>,
groups: Vec<Group>,
selects: Vec<Selector>,
attributes: Vec<Name>,
plans: Vec<Plan>,
namespaced: bool,
}
#[derive(Debug, Clone)]
struct Node {
groups: Range<usize>,
selects: Range<usize>,
attributes: Range<usize>,
leaf: bool,
pending: usize,
}
#[derive(Debug, Clone)]
struct Group {
local: Box<str>,
namespace: Option<Box<str>>,
selects: Range<usize>,
attributes: bool,
}
#[derive(Debug, Clone)]
struct Selector {
select: Select,
node: usize,
}
#[derive(Debug, Clone)]
struct Plan {
chain: Box<[usize]>,
attribute: Option<usize>,
}
impl Paths {
#[must_use]
pub fn new<I: IntoIterator<Item = Path>>(paths: I) -> Self {
let mut tree = Tree::default();
let plans: Vec<(Vec<usize>, Option<(usize, usize)>)> =
paths.into_iter().map(|path| tree.insert(path)).collect();
tree.finish(plans)
}
#[must_use]
pub const fn len(&self) -> usize {
self.plans.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.plans.is_empty()
}
pub fn read<'s, 'a>(&'s self, xml: &'a [u8], slots: &'s mut Slots) -> Values<'s, 'a> {
let Slots {
visits,
attributes,
counts,
scope,
tag,
} = slots;
visits.clear();
visits.resize(self.nodes.len(), Visit::default());
attributes.clear();
attributes.resize(self.attributes.len(), Found::default());
counts.clear();
counts.resize(self.groups.len(), 0);
scope.clear();
if !self.plans.is_empty() {
let _ = Walk {
paths: self,
doc: xml,
visits: visits.as_mut_slice(),
attributes: attributes.as_mut_slice(),
counts: counts.as_mut_slice(),
scope,
tag,
left: self.nodes[0].pending,
}
.document();
}
Values {
paths: self,
visits: visits.as_slice(),
attributes: attributes.as_slice(),
doc: xml,
}
}
fn groups_of(&self, node: usize, local: &[u8]) -> Range<usize> {
let Range { start, end } = self.nodes[node].groups;
let groups = &self.groups[start..end];
let from = groups.partition_point(|g| g.local.as_bytes() < local);
let len = groups[from..]
.iter()
.take_while(|g| g.local.as_bytes() == local)
.count();
start + from..start + from + len
}
}
struct Tree {
children: Vec<Vec<(Name, Select, usize)>>,
attributes: Vec<Vec<Name>>,
leaf: Vec<bool>,
index: HashMap<(usize, Name, Select), usize>,
}
impl Default for Tree {
fn default() -> Self {
Self {
children: vec![Vec::new()],
attributes: vec![Vec::new()],
leaf: vec![false],
index: HashMap::new(),
}
}
}
impl Tree {
fn insert(&mut self, path: Path) -> (Vec<usize>, Option<(usize, usize)>) {
let mut at = 0;
let mut chain = Vec::with_capacity(path.steps.len());
for Step { name, select } in path.steps {
let next = self.children.len();
let node = *self
.index
.entry((at, name.clone(), select.clone()))
.or_insert(next);
if node == next {
self.children.push(Vec::new());
self.attributes.push(Vec::new());
self.leaf.push(false);
self.children[at].push((name, select, next));
}
chain.push(node);
at = node;
}
let attribute = match path.attribute {
None => {
self.leaf[at] = true;
None
}
Some(name) => {
let wanted = &mut self.attributes[at];
let i = wanted.iter().position(|n| *n == name).unwrap_or_else(|| {
wanted.push(name);
wanted.len() - 1
});
Some((at, i))
}
};
(chain, attribute)
}
fn finish(self, plans: Vec<(Vec<usize>, Option<(usize, usize)>)>) -> Paths {
let count = self.children.len();
let mut nodes = Vec::with_capacity(count);
let mut groups: Vec<Group> = Vec::new();
let mut selects = Vec::new();
let mut attributes = Vec::new();
let mut namespaced = false;
for ((mut children, wanted), leaf) in self
.children
.into_iter()
.zip(self.attributes)
.zip(self.leaf)
{
children.sort_unstable();
let first_group = groups.len();
let first_select = selects.len();
for (name, select, node) in children {
namespaced |= name.namespace.is_some();
if let Select::Attribute(attribute, _) = &select {
namespaced |= attribute.namespace.is_some();
}
let fresh = groups.len() == first_group
|| groups.last().is_some_and(|g: &Group| {
*g.local != *name.local || g.namespace != name.namespace
});
if fresh {
groups.push(Group {
attributes: name.namespace.is_some(),
local: name.local,
namespace: name.namespace,
selects: selects.len()..selects.len(),
});
}
if let Some(group) = groups.last_mut() {
group.attributes |= matches!(select, Select::Attribute(..));
group.selects.end += 1;
}
selects.push(Selector { select, node });
}
let first_attribute = attributes.len();
namespaced |= wanted.iter().any(|n| n.namespace.is_some());
attributes.extend(wanted);
nodes.push(Node {
groups: first_group..groups.len(),
selects: first_select..selects.len(),
attributes: first_attribute..attributes.len(),
leaf,
pending: 0,
});
}
for n in (0..count).rev() {
let below: usize = selects[nodes[n].selects.clone()]
.iter()
.map(|s: &Selector| nodes[s.node].pending)
.sum();
let node = &mut nodes[n];
node.pending =
usize::from(n != 0) + usize::from(node.leaf) + node.attributes.len() + below;
}
let plans = plans
.into_iter()
.map(|(chain, attribute)| Plan {
chain: chain.into_boxed_slice(),
attribute: attribute.map(|(node, i)| nodes[node].attributes.start + i),
})
.collect();
Paths {
nodes,
groups,
selects,
attributes,
plans,
namespaced,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Slots {
visits: Vec<Visit>,
attributes: Vec<Found>,
counts: Vec<usize>,
scope: Vec<Binding>,
tag: Vec<Attribute>,
}
impl Slots {
#[must_use]
pub const fn new() -> Self {
Self {
visits: Vec::new(),
attributes: Vec::new(),
counts: Vec::new(),
scope: Vec::new(),
tag: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
struct Visit {
tag: usize,
start: usize,
end: usize,
closed: bool,
kind: Option<Kind>,
}
#[derive(Debug, Clone, Default)]
struct Found {
read: bool,
value: Option<Range<usize>>,
}
pub fn prolog(doc: &[u8]) -> Result<usize, Malformed> {
let mut at = if doc.starts_with(b"\xEF\xBB\xBF") {
3
} else {
0
};
loop {
at = space(doc, at);
if doc.get(at) != Some(&b'<') {
return Err(Malformed);
}
match doc.get(at + 1) {
Some(b'?') => at = find(doc, at + 2, b"?>")? + 2,
Some(b'!') if doc[at..].starts_with(b"<!--") => {
at = find(doc, at + 4, b"-->")? + 3;
}
Some(b'!' | b'/') | None => return Err(Malformed),
Some(_) => return Ok(at),
}
}
}
pub enum TagPart {
Attribute(Attribute),
End { after: usize, closed: bool },
}
pub fn tag_part(doc: &[u8], at: &mut usize) -> Result<TagPart, Malformed> {
let gap = *at;
let mut i = space(doc, gap);
match doc.get(i) {
Some(b'>') => Ok(TagPart::End {
after: i + 1,
closed: false,
}),
Some(b'/') if doc.get(i + 1) == Some(&b'>') => Ok(TagPart::End {
after: i + 2,
closed: true,
}),
Some(_) if i > gap => {
let start = i;
while doc.get(i).is_some_and(|&b| attribute_name_byte(b)) {
i += 1;
}
let name = start..i;
i = space(doc, i);
if name.is_empty() || doc.get(i) != Some(&b'=') {
return Err(Malformed);
}
i = space(doc, i + 1);
let quote = doc
.get(i)
.copied()
.filter(|&b| b == b'"' || b == b'\'')
.ok_or(Malformed)?;
let end = find_byte(doc, i + 1, quote)?;
let value = i + 1..end;
if memchr(b'<', &doc[value.clone()]).is_some() {
return Err(Malformed);
}
*at = end + 1;
Ok(TagPart::Attribute(Attribute { name, value }))
}
_ => Err(Malformed),
}
}
#[derive(Debug, Clone)]
struct Binding {
prefix: Range<usize>,
uri: Range<usize>,
}
#[derive(Debug, Clone)]
pub struct Attribute {
pub name: Range<usize>,
pub value: Range<usize>,
}
#[derive(Debug, Clone, Copy)]
pub struct Values<'s, 'a> {
paths: &'s Paths,
visits: &'s [Visit],
attributes: &'s [Found],
doc: &'a [u8],
}
impl<'a> Values<'_, 'a> {
#[must_use]
pub fn get(&self, i: usize) -> Option<Slot<'a>> {
self.paths.plans.get(i).map(|plan| self.slot(plan))
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Slot<'a>> {
self.paths.plans.iter().map(|plan| self.slot(plan))
}
#[must_use]
pub const fn len(&self) -> usize {
self.paths.plans.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.paths.plans.is_empty()
}
fn slot(&self, plan: &Plan) -> Slot<'a> {
let mut parent = 0;
for (i, &node) in plan.chain.iter().enumerate() {
if self.visits[node].tag == 0 {
let holder = self.visits[parent];
return match (holder.closed, i, holder.kind) {
(false, _, _) => Slot::Malformed,
(true, 0, _) => Slot::MissingRoot,
(true, _, Some(Kind::Text)) => Slot::WrongParentType(i),
(true, _, _) => Slot::MissingField(i),
};
}
parent = node;
}
if let Some(k) = plan.attribute {
let found = &self.attributes[k];
return match (&found.value, found.read) {
(_, false) => Slot::Malformed,
(None, true) => Slot::MissingField(plan.chain.len()),
(Some(range), true) => self.found(range.clone(), Kind::Text, Source::Attribute),
};
}
let visit = self.visits[parent];
match visit.kind {
Some(kind) if visit.closed => self.found(visit.start..visit.end, kind, Source::Content),
_ => Slot::Malformed,
}
}
fn found(&self, range: Range<usize>, kind: Kind, source: Source) -> Slot<'a> {
let start = range.start;
let bytes = &self.doc[range];
let well_formed = match (source, kind) {
(Source::Content, Kind::Element) => true,
(Source::Content, _) => decode_text(bytes, |_| {}).is_ok(),
(Source::Attribute, _) => decode_attribute(bytes, |_| {}).is_ok(),
};
match std::str::from_utf8(bytes) {
Ok(text) if well_formed => Slot::Found(Raw {
text,
kind,
start,
source,
}),
_ => Slot::Malformed,
}
}
}
#[derive(Debug)]
pub struct Malformed;
type Next = Result<Option<usize>, Malformed>;
struct Walk<'p, 'a, 's> {
paths: &'p Paths,
doc: &'a [u8],
visits: &'s mut [Visit],
attributes: &'s mut [Found],
counts: &'s mut [usize],
scope: &'s mut Vec<Binding>,
tag: &'s mut Vec<Attribute>,
left: usize,
}
impl Walk<'_, '_, '_> {
fn document(&mut self) -> Result<(), Malformed> {
self.child(0, prolog(self.doc)?)?;
Ok(())
}
fn child(&mut self, parent: usize, lt: usize) -> Next {
let doc = self.doc;
let paths = self.paths;
let qname = lt + 1..name_end(doc, lt + 1)?;
let local = local_name(&doc[qname.clone()]);
let groups = paths.groups_of(parent, local);
let parse = !groups.is_empty()
&& (paths.namespaced || paths.groups[groups.clone()].iter().any(|g| g.attributes));
let scope = self.scope.len();
let (content, closed) = if parse {
let tag = self.read_tag(qname.end)?;
if paths.namespaced {
self.bind();
}
tag
} else {
tag_end(doc, qname.end)?
};
let mut matched = false;
for g in groups.clone() {
let group = &paths.groups[g];
if let Some(uri) = &group.namespace
&& !self.element_in(&doc[qname.clone()], uri)?
{
continue;
}
let n = self.counts[g];
self.counts[g] += 1;
for selector in &paths.selects[group.selects.clone()] {
if self.visits[selector.node].tag != 0 {
continue;
}
let hit = match &selector.select {
Select::Nth(k) => *k == n,
Select::Attribute(name, value) => self
.attribute(name)?
.map(|range| equal_decoded(&doc[range], value.as_bytes()))
.transpose()?
.unwrap_or(false),
};
if hit {
self.visits[selector.node].tag = lt + 1;
self.left -= 1;
matched = true;
}
}
}
if parent == 0 {
self.visits[0].closed = true;
self.close(0);
if self.left == 0 {
return Ok(None);
}
}
if !matched {
self.scope.truncate(scope);
return if closed {
Ok(Some(content))
} else {
pass(doc, content, None, false).map(|passed| Some(passed.after))
};
}
let mut after = content;
for g in groups {
for selector in &paths.selects[paths.groups[g].selects.clone()] {
if self.visits[selector.node].tag != lt + 1 {
continue;
}
match self.element(selector.node, qname.clone(), content, closed)? {
Some(next) => after = next,
None => return Ok(None),
}
}
}
self.scope.truncate(scope);
Ok(Some(after))
}
fn element(&mut self, node: usize, qname: Range<usize>, content: usize, closed: bool) -> Next {
let doc = self.doc;
let paths = self.paths;
let info = &paths.nodes[node];
if !info.attributes.is_empty() {
self.read_tag(qname.end)?;
for k in info.attributes.clone() {
let value = self.attribute(&paths.attributes[k])?;
self.attributes[k] = Found { read: true, value };
self.left -= 1;
}
if self.left == 0 {
return Ok(None);
}
}
self.visits[node].start = content;
if closed {
self.shut(node, content, Kind::Empty);
return Ok((self.left > 0).then_some(content));
}
let name = &doc[qname];
let mut child = false;
let mut text = false;
let mut at = content;
if !info.groups.is_empty() {
for g in info.groups.clone() {
self.counts[g] = 0;
}
let mut open = info.selects.len();
while open > 0 {
let lt = find_byte(doc, at, b'<')?;
text = text || !blank(&doc[at..lt]);
match doc.get(lt + 1) {
Some(b'/') => {
let after = close_tag(doc, lt, name)?;
self.shut(node, lt, kind(child, text));
return Ok((self.left > 0).then_some(after));
}
Some(b'!' | b'?') => {
let (after, cdata) = markup(doc, lt)?;
text = text || cdata.is_some_and(|c| !blank(&doc[c]));
at = after;
}
Some(_) => {
child = true;
match self.child(node, lt)? {
Some(next) => at = next,
None => return Ok(None),
}
open = paths.selects[info.selects.clone()]
.iter()
.filter(|s| self.visits[s.node].tag == 0)
.count();
}
None => return Err(Malformed),
}
}
}
let passed = pass(doc, at, Some(name), info.leaf)?;
self.shut(
node,
passed.end,
kind(child || passed.child, text || passed.text),
);
Ok((self.left > 0).then_some(passed.after))
}
fn shut(&mut self, node: usize, end: usize, kind: Kind) {
let visit = &mut self.visits[node];
visit.end = end;
visit.kind = Some(kind);
visit.closed = true;
self.close(node);
}
fn close(&mut self, node: usize) {
let paths = self.paths;
let info = &paths.nodes[node];
let mut settled = usize::from(info.leaf);
for selector in &paths.selects[info.selects.clone()] {
if self.visits[selector.node].tag == 0 {
settled += paths.nodes[selector.node].pending;
}
}
self.left -= settled;
}
fn read_tag(&mut self, from: usize) -> Result<(usize, bool), Malformed> {
self.tag.clear();
let mut at = from;
loop {
match tag_part(self.doc, &mut at)? {
TagPart::Attribute(attribute) => self.tag.push(attribute),
TagPart::End { after, closed } => return Ok((after, closed)),
}
}
}
fn bind(&mut self) {
let doc = self.doc;
for attribute in self.tag.as_slice() {
let name = &doc[attribute.name.clone()];
let prefix = if name == b"xmlns" {
attribute.name.end..attribute.name.end
} else if name.starts_with(b"xmlns:") {
attribute.name.start + 6..attribute.name.end
} else {
continue;
};
self.scope.push(Binding {
prefix,
uri: attribute.value.clone(),
});
}
}
fn element_in(&self, qname: &[u8], uri: &str) -> Result<bool, Malformed> {
let prefix = memchr(b':', qname).map_or(&qname[..0], |i| &qname[..i]);
self.prefix_in(prefix, uri)
}
fn prefix_in(&self, prefix: &[u8], uri: &str) -> Result<bool, Malformed> {
if prefix == b"xml" {
return Ok(uri == XML_NAMESPACE);
}
let doc = self.doc;
let bound = self
.scope
.iter()
.rev()
.find(|b| &doc[b.prefix.clone()] == prefix);
match bound {
None if prefix.is_empty() => Ok(false),
None => Err(Malformed),
Some(b) => equal_decoded(&doc[b.uri.clone()], uri.as_bytes()),
}
}
fn attribute(&self, name: &Name) -> Result<Option<Range<usize>>, Malformed> {
let doc = self.doc;
for attribute in self.tag.as_slice() {
let qname = &doc[attribute.name.clone()];
if qname == b"xmlns" || qname.starts_with(b"xmlns:") {
continue;
}
if local_name(qname) != name.local.as_bytes() {
continue;
}
let hit = match (&name.namespace, memchr(b':', qname)) {
(None, _) => true,
(Some(_), None) => false,
(Some(uri), Some(i)) => self.prefix_in(&qname[..i], uri)?,
};
if hit {
return Ok(Some(attribute.value.clone()));
}
}
Ok(None)
}
}
const fn kind(child: bool, text: bool) -> Kind {
match (child, text) {
(true, _) => Kind::Element,
(false, true) => Kind::Text,
(false, false) => Kind::Empty,
}
}
pub struct Passed {
pub end: usize,
pub after: usize,
pub child: bool,
text: bool,
}
pub fn pass(
doc: &[u8],
mut at: usize,
name: Option<&[u8]>,
track: bool,
) -> Result<Passed, Malformed> {
let mut depth = 1_usize;
let mut child = false;
let mut text = false;
loop {
let lt = find_byte(doc, at, b'<')?;
if track && depth == 1 && !text {
text = !blank(&doc[at..lt]);
}
match doc.get(lt + 1) {
Some(b'/') => {
depth -= 1;
if depth == 0 {
let after = match name {
Some(name) => close_tag(doc, lt, name)?,
None => find_byte(doc, lt + 2, b'>')? + 1,
};
return Ok(Passed {
end: lt,
after,
child,
text,
});
}
at = find_byte(doc, lt + 2, b'>')? + 1;
}
Some(b'!' | b'?') => {
let (after, cdata) = markup(doc, lt)?;
if track && depth == 1 && !text {
text = cdata.is_some_and(|c| !blank(&doc[c]));
}
at = after;
}
Some(_) => {
let (after, closed) = tag_end(doc, lt + 1)?;
child |= depth == 1;
depth += usize::from(!closed);
at = after;
}
None => return Err(Malformed),
}
}
}
pub fn markup(doc: &[u8], lt: usize) -> Result<(usize, Option<Range<usize>>), Malformed> {
let rest = &doc[lt..];
if rest.starts_with(b"<?") {
Ok((find(doc, lt + 2, b"?>")? + 2, None))
} else if rest.starts_with(b"<!--") {
Ok((find(doc, lt + 4, b"-->")? + 3, None))
} else if rest.starts_with(b"<![CDATA[") {
let end = find(doc, lt + 9, b"]]>")?;
Ok((end + 3, Some(lt + 9..end)))
} else {
Err(Malformed)
}
}
pub fn close_tag(doc: &[u8], lt: usize, name: &[u8]) -> Result<usize, Malformed> {
let from = lt + 2;
let end = from + name.len();
if doc.get(from..end) != Some(name) {
return Err(Malformed);
}
let at = space(doc, end);
if doc.get(at) != Some(&b'>') {
return Err(Malformed);
}
Ok(at + 1)
}
pub fn tag_end(doc: &[u8], mut from: usize) -> Result<(usize, bool), Malformed> {
loop {
let rest = doc.get(from..).ok_or(Malformed)?;
let i = memchr3(b'"', b'\'', b'>', rest).ok_or(Malformed)?;
let at = from + i;
if doc[at] == b'>' {
return Ok((at + 1, at > 0 && doc[at - 1] == b'/'));
}
from = find_byte(doc, at + 1, doc[at])? + 1;
}
}
pub fn name_end(doc: &[u8], from: usize) -> Result<usize, Malformed> {
let rest = doc.get(from..).ok_or(Malformed)?;
let len = rest
.iter()
.position(|&b| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'/' | b'>'))
.ok_or(Malformed)?;
if len == 0 {
return Err(Malformed);
}
Ok(from + len)
}
pub fn local_name(qname: &[u8]) -> &[u8] {
memchr(b':', qname).map_or(qname, |i| &qname[i + 1..])
}
const fn attribute_name_byte(b: u8) -> bool {
!matches!(
b,
b' ' | b'\t' | b'\n' | b'\r' | b'=' | b'>' | b'/' | b'"' | b'\'' | b'<'
)
}
#[inline]
pub fn find_byte(doc: &[u8], from: usize, byte: u8) -> Result<usize, Malformed> {
let rest = doc.get(from..).ok_or(Malformed)?;
memchr(byte, rest).map(|i| from + i).ok_or(Malformed)
}
fn find(doc: &[u8], from: usize, needle: &[u8]) -> Result<usize, Malformed> {
let rest = doc.get(from..).ok_or(Malformed)?;
memmem::find(rest, needle)
.map(|i| from + i)
.ok_or(Malformed)
}
#[inline]
fn space(doc: &[u8], mut at: usize) -> usize {
while let Some(b' ' | b'\t' | b'\n' | b'\r') = doc.get(at) {
at += 1;
}
at
}
fn blank(text: &[u8]) -> bool {
let mut at = 0;
while let Some(&b) = text.get(at) {
match b {
b' ' | b'\t' | b'\n' | b'\r' => at += 1,
b'&' => match entity(&text[at + 1..]) {
Some((' ' | '\t' | '\n' | '\r', len)) => at += 1 + len,
_ => return false,
},
_ => return false,
}
}
true
}
pub const fn attribute_special(b: u8) -> bool {
matches!(b, b'&' | b'\t' | b'\n' | b'\r' | b'<')
}
fn entity(raw: &[u8]) -> Option<(char, usize)> {
let semi = memchr(b';', &raw[..raw.len().min(32)])?;
let name = &raw[..semi];
let c = match name {
b"lt" => '<',
b"gt" => '>',
b"amp" => '&',
b"apos" => '\'',
b"quot" => '"',
[b'#', b'x', hex @ ..] => code(hex, 16)?,
[b'#', digits @ ..] => code(digits, 10)?,
_ => return None,
};
Some((c, semi + 1))
}
fn code(digits: &[u8], radix: u32) -> Option<char> {
if digits.is_empty() {
return None;
}
let value = digits.iter().try_fold(0_u32, |acc, &b| {
let digit = char::from(b).to_digit(radix)?;
acc.checked_mul(radix)?.checked_add(digit)
})?;
let c = char::from_u32(value)?;
let allowed =
matches!(c, '\t' | '\n' | '\r') || (c >= ' ' && !matches!(c, '\u{FFFE}' | '\u{FFFF}'));
allowed.then_some(c)
}
fn line_ends(mut run: &[u8], out: &mut impl FnMut(&[u8])) {
while let Some(i) = memchr(b'\r', run) {
out(&run[..i]);
out(b"\n");
let skip = if run.get(i + 1) == Some(&b'\n') { 2 } else { 1 };
run = &run[i + skip..];
}
out(run);
}
pub fn decode_text(raw: &[u8], mut out: impl FnMut(&[u8])) -> Result<(), Malformed> {
let mut at = 0;
while at < raw.len() {
let Some(i) = memchr2(b'&', b'<', &raw[at..]) else {
line_ends(&raw[at..], &mut out);
return Ok(());
};
line_ends(&raw[at..at + i], &mut out);
at += i;
if raw[at] == b'&' {
let (c, len) = entity(&raw[at + 1..]).ok_or(Malformed)?;
out(c.encode_utf8(&mut [0; 4]).as_bytes());
at += 1 + len;
} else {
let (after, cdata) = markup(raw, at)?;
if let Some(range) = cdata {
line_ends(&raw[range], &mut out);
}
at = after;
}
}
Ok(())
}
pub fn decode_attribute(raw: &[u8], mut out: impl FnMut(&[u8])) -> Result<(), Malformed> {
let mut at = 0;
loop {
let rest = &raw[at..];
let Some(i) = rest.iter().position(|&b| attribute_special(b)) else {
out(rest);
return Ok(());
};
out(&rest[..i]);
at += i;
match raw[at] {
b'&' => {
let (c, len) = entity(&raw[at + 1..]).ok_or(Malformed)?;
out(c.encode_utf8(&mut [0; 4]).as_bytes());
at += 1 + len;
}
b'<' => return Err(Malformed),
b'\r' if raw.get(at + 1) == Some(&b'\n') => {
out(b" ");
at += 2;
}
_ => {
out(b" ");
at += 1;
}
}
}
}
pub fn equal_decoded(raw: &[u8], want: &[u8]) -> Result<bool, Malformed> {
if !raw.iter().any(|&b| attribute_special(b)) {
return Ok(raw == want);
}
let mut at = 0;
let mut equal = true;
decode_attribute(raw, |part| {
if equal && want.get(at..at + part.len()) == Some(part) {
at += part.len();
} else {
equal = false;
}
})?;
Ok(equal && at == want.len())
}
#[cfg(test)]
mod tests;