use std::borrow::Cow;
use std::collections::HashMap;
use quick_xml::Reader;
use quick_xml::events::Event;
const NONE: u32 = u32::MAX;
const MAX_DEPTH: usize = 512;
struct El<'a> {
name: Cow<'a, [u8]>,
attrs: (u32, u32),
text: Cow<'a, [u8]>,
parent: u32,
first: u32,
last: u32,
next: u32,
}
pub(super) struct Dom<'a> {
els: Vec<El<'a>>,
attrs: Vec<Attr<'a>>,
ids: HashMap<String, u32>,
docs: Vec<Doc>,
home: Vec<String>,
}
type Attr<'a> = (Cow<'a, [u8]>, Cow<'a, str>);
struct Doc {
start: u32,
path: String,
ids: HashMap<String, u32>,
}
pub(super) struct Children<'d, 'a> {
dom: &'d Dom<'a>,
at: u32,
}
impl Iterator for Children<'_, '_> {
type Item = usize;
fn next(&mut self) -> Option<usize> {
if self.at == NONE {
return None;
}
let e = self.at as usize;
self.at = self.dom.els[e].next;
Some(e)
}
}
impl<'a> Dom<'a> {
pub(super) fn parse(bytes: &'a [u8]) -> Self {
let mut dom = Dom {
els: Vec::new(),
attrs: Vec::new(),
ids: HashMap::new(),
docs: Vec::new(),
home: Vec::new(),
};
let mut reader = Reader::from_reader(bytes);
let config = reader.config_mut();
config.check_end_names = false;
config.allow_unmatched_ends = true;
config.check_comments = false;
let mut stack: Vec<u32> = Vec::new();
let mut skipped = 0usize;
loop {
let event = match reader.read_event() {
Ok(Event::Eof) | Err(_) => break,
Ok(e) => e,
};
match event {
Event::Start(e) => {
if skipped > 0 || stack.len() >= MAX_DEPTH {
skipped += 1;
} else {
let id = dom.push(within(bytes, &e), stack.last().copied());
stack.push(id);
}
}
Event::Empty(e) => {
if skipped == 0 && stack.len() < MAX_DEPTH {
dom.push(within(bytes, &e), stack.last().copied());
}
}
Event::End(_) => {
if skipped > 0 {
skipped -= 1;
} else {
stack.pop();
}
}
Event::Text(t) if skipped == 0 => {
if let Some(&top) = stack.last() {
dom.append(top, t.into_inner());
}
}
Event::CData(t) if skipped == 0 => {
if let Some(&top) = stack.last() {
dom.append(top, t.into_inner());
}
}
Event::GeneralRef(r) if skipped == 0 => {
if let Some(&top) = stack.last() {
let resolved = resolve_reference(&r);
dom.append(top, Cow::Owned(resolved));
}
}
_ => {}
}
}
for k in 0..dom.els.len() {
if let Some(v) = dom.attr(k, "id") {
dom.ids.entry(v.to_owned()).or_insert(u32_of(k));
}
}
dom
}
fn push(&mut self, raw: Cow<'a, [u8]>, parent: Option<u32>) -> u32 {
let from = u32_of(self.attrs.len());
let name = split_tag(raw, &mut self.attrs);
let id = u32_of(self.els.len());
self.els.push(El {
name,
attrs: (from, u32_of(self.attrs.len())),
text: Cow::Borrowed(&[]),
parent: parent.unwrap_or(NONE),
first: NONE,
last: NONE,
next: NONE,
});
if let Some(p) = parent {
let p = p as usize;
if self.els[p].last == NONE {
self.els[p].first = id;
} else {
let last = self.els[p].last as usize;
self.els[last].next = id;
}
self.els[p].last = id;
}
id
}
fn append(&mut self, e: u32, chunk: Cow<'a, [u8]>) {
let text = &mut self.els[e as usize].text;
if chunk.iter().all(u8::is_ascii_whitespace) && text.iter().all(u8::is_ascii_whitespace) {
if text.is_empty() {
*text = chunk;
}
return;
}
if text.iter().all(u8::is_ascii_whitespace) {
*text = chunk;
} else {
text.to_mut().extend_from_slice(&chunk);
}
}
pub(super) fn root(&self) -> Option<usize> {
(!self.els.is_empty()).then_some(0)
}
pub(super) fn name(&self, e: usize) -> &[u8] {
&self.els[e].name
}
pub(super) fn is(&self, e: usize, name: &str) -> bool {
self.els[e].name.as_ref() == name.as_bytes()
}
pub(super) fn parent(&self, e: usize) -> Option<usize> {
let p = self.els[e].parent;
(p != NONE).then_some(p as usize)
}
pub(super) fn attr(&self, e: usize, name: &str) -> Option<&str> {
self.attrs_of(e)
.iter()
.find(|(n, _)| n.as_ref() == name.as_bytes())
.map(|(_, v)| v.as_ref())
}
fn attrs_of(&self, e: usize) -> &[Attr<'a>] {
let (from, to) = self.els[e].attrs;
&self.attrs[from as usize..to as usize]
}
pub(super) fn attr_num<T: std::str::FromStr>(&self, e: usize, name: &str) -> Option<T> {
self.attr(e, name)?.trim().parse().ok()
}
pub(super) fn children(&self, e: usize) -> Children<'_, 'a> {
Children {
dom: self,
at: self.els[e].first,
}
}
pub(super) fn kids<'s>(&'s self, e: usize, name: &'s str) -> impl Iterator<Item = usize> + 's {
self.children(e).filter(move |&c| self.is(c, name))
}
pub(super) fn child(&self, e: usize, name: &str) -> Option<usize> {
self.children(e).find(|&c| self.is(c, name))
}
pub(super) fn path(&self, e: usize, names: &[&str]) -> Option<usize> {
names.iter().try_fold(e, |at, n| self.child(at, n))
}
pub(super) fn descendant(&self, e: usize, name: &str, depth: usize) -> Option<usize> {
let mut level = vec![e];
for _ in 0..depth {
let mut next = Vec::new();
for &at in &level {
for c in self.children(at) {
if self.is(c, name) {
return Some(c);
}
next.push(c);
}
}
if next.is_empty() {
break;
}
level = next;
}
None
}
pub(super) fn text(&self, e: usize) -> &[u8] {
self.els[e].text.trim_ascii()
}
pub(super) fn string(&self, e: usize) -> &str {
std::str::from_utf8(self.text(e)).unwrap_or("")
}
pub(super) fn child_string(&self, e: usize, name: &str) -> Option<&str> {
self.child(e, name).map(|c| self.string(c))
}
pub(super) fn by_id(&self, id: &str) -> Option<usize> {
self.ids.get(id).map(|&e| e as usize)
}
pub(super) fn by_id_at(&self, e: usize, id: &str) -> Option<usize> {
self.ids_of(e).get(id).map(|&k| k as usize).or_else(|| self.by_id(id))
}
pub(super) fn len(&self) -> usize {
self.els.len()
}
fn doc_of(&self, e: usize) -> Option<&Doc> {
let k = self.docs.partition_point(|d| d.start as usize <= e);
k.checked_sub(1).map(|k| &self.docs[k])
}
pub(super) fn path_of(&self, e: usize) -> &str {
self.doc_of(e).map_or("", |d| d.path.as_str())
}
pub(super) fn dir_of(&self, e: usize) -> &str {
let path = self.path_of(e);
path.rfind('/').map_or("", |k| &path[..=k])
}
pub(super) fn set_home(&mut self, path: &str, dir: &str) {
self.home = dir
.split('/')
.filter(|p| !p.is_empty() && *p != ".")
.map(str::to_owned)
.collect();
self.set_path(path);
}
fn set_path(&mut self, path: &str) {
if self.docs.is_empty() {
self.docs.push(Doc {
start: 0,
path: path.to_owned(),
ids: HashMap::new(),
});
}
}
pub(super) fn has(&self, path: &str) -> bool {
self.docs.iter().any(|d| d.path == path)
}
pub(super) fn absorb(&mut self, path: &str, other: Dom<'_>) {
let start = u32_of(self.els.len());
let shift = |k: u32| if k == NONE { NONE } else { k + start };
let base = u32_of(self.attrs.len());
self.attrs.extend(
other
.attrs
.into_iter()
.map(|(k, v)| (Cow::Owned(k.into_owned()), Cow::Owned(v.into_owned()))),
);
for el in other.els {
self.els.push(El {
name: Cow::Owned(el.name.into_owned()),
attrs: (el.attrs.0 + base, el.attrs.1 + base),
text: Cow::Owned(el.text.into_owned()),
parent: shift(el.parent),
first: shift(el.first),
last: shift(el.last),
next: shift(el.next),
});
}
let ids = other.ids.into_iter().map(|(k, v)| (k, v + start)).collect();
self.set_path("");
self.docs.push(Doc {
start,
path: path.to_owned(),
ids,
});
}
pub(super) fn document(&self, e: usize, url: &str) -> Option<String> {
let url = url.trim();
let (path, _) = url.split_once('#')?;
let path = percent_decode(path).replace('\\', "/");
if path.is_empty() || path.contains("://") || path.starts_with('/') || path.as_bytes().get(1) == Some(&b':') {
return None;
}
let mut full = join(self.dir_of(e), &path);
let up = full.split('/').take_while(|p| *p == "..").count();
if up > 0 && up <= self.home.len() {
let parts: Vec<&str> = full.split('/').skip(up).collect();
if parts.len() > up
&& parts[..up]
.iter()
.zip(&self.home[self.home.len() - up..])
.all(|(a, b)| a == b)
{
full = parts[up..].join("/");
}
}
(full != self.path_of(e)).then_some(full)
}
pub(super) fn url_at(&self, e: usize, url: &str) -> Option<usize> {
let url = url.trim();
let (ids, id) = match url.split_once('#') {
Some(("", id)) => (self.ids_of(e), id),
Some((_, id)) => match self.document(e, url) {
None => (self.ids_of(e), id),
Some(path) => {
let doc = self.docs.iter().find(|d| d.path == path)?;
(if doc.start == 0 { &self.ids } else { &doc.ids }, id)
}
},
None => (self.ids_of(e), url),
};
ids.get(id).map(|&k| k as usize).or_else(|| {
let decoded = percent_decode(id);
(decoded != id)
.then(|| ids.get(&decoded).map(|&k| k as usize))
.flatten()
})
}
fn ids_of(&self, e: usize) -> &HashMap<String, u32> {
match self.doc_of(e) {
Some(d) if d.start != 0 => &d.ids,
_ => &self.ids,
}
}
pub(super) fn link(&self, e: usize, name: &str) -> Option<usize> {
self.url_at(e, self.attr(e, name)?)
}
pub(super) fn wanted(&self, from: usize) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for e in from..self.els.len() {
let mut add = |url: &str| {
if let Some(path) = self.document(e, url)
&& !self.has(&path)
&& !out.contains(&path)
{
out.push(path);
}
};
for (k, v) in self.attrs_of(e) {
if matches!(k.as_ref(), b"url" | b"source" | b"target") && v.contains('#') {
add(v);
}
}
if self.is(e, "skeleton") {
add(self.string(e));
}
}
out
}
pub(super) fn by_sid(&self, e: usize, sid: &str) -> Option<usize> {
let mut queue = std::collections::VecDeque::from([e]);
let mut seen = 0usize;
while let Some(at) = queue.pop_front() {
for c in self.children(at) {
if self.attr(c, "sid") == Some(sid) {
return Some(c);
}
queue.push_back(c);
}
seen += 1;
if seen > 1_000_000 {
break;
}
}
None
}
}
fn within<'a>(doc: &'a [u8], tag: &[u8]) -> Cow<'a, [u8]> {
let base = doc.as_ptr() as usize;
let start = tag.as_ptr() as usize;
match start.checked_sub(base) {
Some(off) if off.checked_add(tag.len()).is_some_and(|end| end <= doc.len()) => {
Cow::Borrowed(&doc[off..off + tag.len()])
}
_ => Cow::Owned(tag.to_vec()),
}
}
#[allow(clippy::type_complexity, reason = "a name and its attributes")]
fn split_tag<'a>(raw: Cow<'a, [u8]>, attrs: &mut Vec<Attr<'a>>) -> Cow<'a, [u8]> {
match raw {
Cow::Borrowed(b) => split_borrowed(b, attrs),
Cow::Owned(v) => {
let mut own = Vec::new();
let name = split_borrowed(&v, &mut own).into_owned();
attrs.extend(
own.into_iter()
.map(|(k, v)| (Cow::Owned(k.into_owned()), Cow::Owned(v.into_owned()))),
);
Cow::Owned(name)
}
}
}
fn split_borrowed<'a>(b: &'a [u8], attrs: &mut Vec<Attr<'a>>) -> Cow<'a, [u8]> {
let end = b.iter().position(u8::is_ascii_whitespace).unwrap_or(b.len());
let name = local(&b[..end]);
let mut i = end;
let n = b.len();
while i < n {
while i < n && b[i].is_ascii_whitespace() {
i += 1;
}
let k0 = i;
while i < n && b[i] != b'=' && !b[i].is_ascii_whitespace() {
i += 1;
}
let key = &b[k0..i];
while i < n && b[i].is_ascii_whitespace() {
i += 1;
}
if i >= n || b[i] != b'=' {
if key.is_empty() {
break;
}
continue;
}
i += 1;
while i < n && b[i].is_ascii_whitespace() {
i += 1;
}
if i >= n {
break;
}
let quote = b[i];
let value = if quote == b'"' || quote == b'\'' {
i += 1;
let v0 = i;
while i < n && b[i] != quote {
i += 1;
}
let v = &b[v0..i];
i += 1;
v
} else {
let v0 = i;
while i < n && !b[i].is_ascii_whitespace() {
i += 1;
}
&b[v0..i]
};
if !key.is_empty() {
attrs.push((Cow::Borrowed(local(key)), unescape(value)));
}
}
Cow::Borrowed(name)
}
fn local(name: &[u8]) -> &[u8] {
if name.starts_with(b"xml:") {
return name;
}
match name.iter().rposition(|&c| c == b':') {
Some(k) => &name[k + 1..],
None => name,
}
}
pub(super) fn unescape(v: &[u8]) -> Cow<'_, str> {
if !v.contains(&b'&') {
return String::from_utf8_lossy(v);
}
let mut out = Vec::with_capacity(v.len());
let mut i = 0;
while i < v.len() {
if v[i] == b'&'
&& let Some(len) = v[i + 1..].iter().take(12).position(|&c| c == b';')
{
out.extend(resolve_reference(&v[i + 1..i + 1 + len]));
i += len + 2;
continue;
}
out.push(v[i]);
i += 1;
}
Cow::Owned(String::from_utf8_lossy(&out).into_owned())
}
fn resolve_reference(name: &[u8]) -> Vec<u8> {
let fixed: &[u8] = match name {
b"amp" => b"&",
b"lt" => b"<",
b"gt" => b">",
b"quot" => b"\"",
b"apos" => b"'",
_ => {
let code = match name {
[b'#', b'x' | b'X', hex @ ..] => std::str::from_utf8(hex)
.ok()
.and_then(|h| u32::from_str_radix(h, 16).ok()),
[b'#', dec @ ..] => std::str::from_utf8(dec).ok().and_then(|d| d.parse().ok()),
_ => None,
};
if let Some(c) = code.and_then(char::from_u32) {
return c.to_string().into_bytes();
}
let mut v = Vec::with_capacity(name.len() + 2);
v.push(b'&');
v.extend_from_slice(name);
v.push(b';');
return v;
}
};
fixed.to_vec()
}
pub(super) fn join(dir: &str, path: &str) -> String {
let mut parts: Vec<&str> = Vec::new();
for p in dir.split('/').chain(path.split('/')) {
match p {
"" | "." => {}
".." if parts.last().is_some_and(|l| *l != "..") => {
parts.pop();
}
p => parts.push(p),
}
}
parts.join("/")
}
pub(super) fn percent_decode(s: &str) -> String {
if !s.contains('%') {
return s.to_owned();
}
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& i + 2 < b.len()
&& let (Some(h), Some(l)) = (hex(b[i + 1]), hex(b[i + 2]))
{
out.push(h * 16 + l);
i += 3;
continue;
}
out.push(b[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn hex(c: u8) -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
b'A'..=b'F' => Some(c - b'A' + 10),
_ => None,
}
}
pub(super) fn from_hex(text: &[u8]) -> Option<Vec<u8>> {
let digits: Vec<u8> = text.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect();
if !digits.len().is_multiple_of(2) {
return None;
}
digits
.chunks_exact(2)
.map(|p| Some(hex(p[0])? * 16 + hex(p[1])?))
.collect()
}
#[allow(
clippy::cast_possible_truncation,
reason = "the tree is far smaller than 2^32 elements"
)]
fn u32_of(n: usize) -> u32 {
n as u32
}
const POW10: [f64; 23] = [
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20,
1e21, 1e22,
];
pub(super) fn floats(text: &[u8], out: &mut Vec<f64>) {
let n = text.len();
let mut i = 0;
loop {
while i < n && text[i] <= b' ' {
i += 1;
}
if i >= n {
break;
}
let start = i;
while i < n && text[i] > b' ' {
i += 1;
}
out.push(float(&text[start..i]));
}
}
pub(super) fn floats32(text: &[u8]) -> Vec<f32> {
let n = text.len();
let mut out = Vec::with_capacity(n / 6);
let mut i = 0;
loop {
while i < n && text[i] <= b' ' {
i += 1;
}
if i >= n {
break;
}
let start = i;
while i < n && text[i] > b' ' {
i += 1;
}
let v = crate::num::f32_of(float(&text[start..i]));
out.push(if v.is_finite() { v } else { 0.0 });
}
out
}
pub(super) fn float(t: &[u8]) -> f64 {
let n = t.len();
let mut i = 0;
let neg = match t.first() {
Some(b'-') => {
i = 1;
true
}
Some(b'+') => {
i = 1;
false
}
_ => false,
};
let mut mant: u64 = 0;
let mut digits = 0u32;
let mut seen = false;
let mut exp: i32 = 0;
let mut exact = true;
while i < n && t[i].is_ascii_digit() {
seen = true;
if digits < 19 {
mant = mant * 10 + u64::from(t[i] - b'0');
if mant != 0 {
digits += 1;
}
} else {
exact = false;
}
i += 1;
}
if i < n && t[i] == b'.' {
i += 1;
while i < n && t[i].is_ascii_digit() {
seen = true;
if digits < 19 {
mant = mant * 10 + u64::from(t[i] - b'0');
if mant != 0 {
digits += 1;
}
exp -= 1;
} else {
exact = false;
}
i += 1;
}
}
if seen && i < n && (t[i] == b'e' || t[i] == b'E') {
i += 1;
let eneg = match t.get(i) {
Some(b'-') => {
i += 1;
true
}
Some(b'+') => {
i += 1;
false
}
_ => false,
};
let mut e: i32 = 0;
let e0 = i;
while i < n && t[i].is_ascii_digit() {
e = (e * 10 + i32::from(t[i] - b'0')).min(100_000);
i += 1;
}
if i == e0 {
exact = false;
}
exp += if eneg { -e } else { e };
}
if !seen || i != n || !exact {
return slow(t);
}
if mant == 0 {
return if neg { -0.0 } else { 0.0 };
}
if mant >= 1 << 53 || !(-22..=22).contains(&exp) {
return slow(t);
}
#[allow(clippy::cast_precision_loss, reason = "below 2^53, exactly")]
let m = mant as f64;
let e = POW10[exp.unsigned_abs() as usize];
let v = if exp >= 0 { m * e } else { m / e };
if neg { -v } else { v }
}
#[cold]
fn slow(t: &[u8]) -> f64 {
std::str::from_utf8(t)
.ok()
.and_then(|s| s.parse::<f64>().ok())
.or_else(|| {
let s = std::str::from_utf8(t).ok()?;
if s.contains("INF") {
Some(if s.starts_with('-') {
f64::NEG_INFINITY
} else {
f64::INFINITY
})
} else {
None
}
})
.or_else(|| {
let comma = |c: &u8| *c == b',';
if t.contains(&b'.')
|| t.iter()
.position(comma)
.is_none_or(|i| t.iter().rposition(comma) != Some(i))
{
return None;
}
let s: String = t.iter().map(|&c| if c == b',' { '.' } else { char::from(c) }).collect();
s.parse::<f64>().ok()
})
.unwrap_or(0.0)
}
pub(super) fn indices(text: &[u8]) -> Vec<u32> {
let n = text.len();
let mut out = Vec::with_capacity(n / 3);
let mut i = 0;
loop {
while i < n && text[i] <= b' ' {
i += 1;
}
if i >= n {
break;
}
let mut v: u64 = 0;
let mut ok = true;
let start = i;
while i < n && text[i] > b' ' {
let c = text[i];
if c.is_ascii_digit() {
v = (v * 10 + u64::from(c - b'0')).min(u64::from(u32::MAX));
} else {
ok = false;
}
i += 1;
}
if !ok {
let tok = &text[start..i];
let f = float(tok);
ok = f >= 0.0 && f.fract() == 0.0 && f < f64::from(u32::MAX);
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "checked just above"
)]
if ok {
v = f as u64;
}
}
out.push(if ok {
u32::try_from(v).unwrap_or(u32::MAX)
} else {
u32::MAX
});
}
out
}
pub(super) fn ints(text: &[u8]) -> Vec<i64> {
let mut out = Vec::new();
for tok in text.split(|c| *c <= b' ').filter(|t| !t.is_empty()) {
let v = std::str::from_utf8(tok)
.ok()
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(-1);
out.push(v);
}
out
}
pub(super) fn words(text: &[u8]) -> impl Iterator<Item = &str> {
text.split(|c| *c <= b' ')
.filter(|t| !t.is_empty())
.map(|t| std::str::from_utf8(t).unwrap_or(""))
}