use std::borrow::Cow;
pub mod queryselector;
mod stream;
mod util;
pub use queryselector::Selector;
pub type InnerNodeHandle = u32;
const VOID: [&str; 15] = [
"area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track",
"wbr",
];
#[derive(Debug, Clone, Default, Eq)]
pub struct Bytes<'a>(Cow<'a, [u8]>);
#[derive(Debug)]
pub enum SetBytesError {
LengthOverflow,
}
impl Bytes<'_> {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn as_utf8_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(&self.0)
}
#[must_use]
pub fn try_as_utf8_str(&self) -> Option<&str> {
std::str::from_utf8(&self.0).ok()
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
#[must_use]
pub fn as_ptr(&self) -> *const u8 {
self.0.as_ptr()
}
pub fn set<B: Into<Vec<u8>>>(&mut self, data: B) -> Result<Option<Box<[u8]>>, SetBytesError> {
self.0 = Cow::Owned(data.into());
Ok(None)
}
}
impl std::hash::Hash for Bytes<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl PartialEq for Bytes<'_> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl PartialEq<str> for Bytes<'_> {
fn eq(&self, other: &str) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl PartialEq<&str> for Bytes<'_> {
fn eq(&self, other: &&str) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl PartialEq<[u8]> for Bytes<'_> {
fn eq(&self, other: &[u8]) -> bool {
self.as_bytes() == other
}
}
impl PartialEq<&[u8]> for Bytes<'_> {
fn eq(&self, other: &&[u8]) -> bool {
self.as_bytes() == *other
}
}
impl<'a> From<&'a str> for Bytes<'a> {
fn from(value: &'a str) -> Self {
Self(Cow::Borrowed(value.as_bytes()))
}
}
impl<'a> From<&'a [u8]> for Bytes<'a> {
fn from(value: &'a [u8]) -> Self {
Self(Cow::Borrowed(value))
}
}
impl TryFrom<String> for Bytes<'static> {
type Error = SetBytesError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Ok(Self(Cow::Owned(value.into_bytes())))
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ParserOptions;
impl ParserOptions {
#[must_use]
pub const fn new() -> Self {
Self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseError {
InvalidLength,
}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("the input length exceeds the capacity of the parser")
}
}
impl std::error::Error for ParseError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeHandle(u32);
impl NodeHandle {
#[must_use]
pub const fn new(node: u32) -> Self {
Self(node)
}
#[must_use]
pub fn get<'p, 'buf>(&self, parser: &'p Parser<'buf>) -> Option<&'p Node<'buf>> {
parser.tags.get(self.0 as usize)
}
pub fn get_mut<'p, 'buf>(&self, parser: &'p mut Parser<'buf>) -> Option<&'p mut Node<'buf>> {
parser.tags.get_mut(self.0 as usize)
}
#[must_use]
pub const fn get_inner(&self) -> u32 {
self.0
}
}
pub type RawChildren = smallvec::SmallVec<[NodeHandle; 4]>;
#[derive(Debug, Clone, Default)]
pub struct Attributes<'a> {
raw: Vec<(Bytes<'a>, Option<Bytes<'a>>)>,
}
impl<'a> Attributes<'a> {
#[must_use]
pub const fn len(&self) -> usize {
self.raw.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.raw.is_empty()
}
pub fn get<B: Into<Bytes<'a>>>(&self, key: B) -> Option<Option<&Bytes<'a>>> {
let key = key.into();
self.raw
.iter()
.find(|(name, _)| *name == key)
.map(|(_, value)| value.as_ref())
}
pub fn contains<B: Into<Bytes<'a>>>(&self, key: B) -> bool {
self.get(key).is_some()
}
pub fn remove<B: Into<Bytes<'a>>>(&mut self, key: B) -> Option<Option<Bytes<'a>>> {
let key = key.into();
let index = self.raw.iter().position(|(name, _)| *name == key)?;
Some(self.raw.remove(index).1)
}
pub fn iter(&self) -> impl Iterator<Item = (Cow<'_, str>, Option<Cow<'_, str>>)> + '_ {
self.raw
.iter()
.map(|(name, value)| (name.as_utf8_str(), value.as_ref().map(Bytes::as_utf8_str)))
}
pub fn is_class_member<B: AsRef<[u8]>>(&self, member: B) -> bool {
self.class().is_some_and(|class| {
class
.as_utf8_str()
.split_ascii_whitespace()
.any(|name| name.as_bytes() == member.as_ref())
})
}
#[must_use]
pub fn id(&self) -> Option<&Bytes<'a>> {
self.get("id").flatten()
}
#[must_use]
pub fn class(&self) -> Option<&Bytes<'a>> {
self.get("class").flatten()
}
}
#[derive(Debug, Clone)]
pub struct HTMLTag<'a> {
name: Bytes<'a>,
attributes: Attributes<'a>,
children: RawChildren,
raw: Bytes<'a>,
id: u32,
subtree_end: u32,
}
impl<'a> HTMLTag<'a> {
#[must_use]
pub const fn children(&self) -> Children<'a, '_> {
Children(self)
}
#[cfg(test)]
pub(crate) const fn children_mut(&mut self) -> ChildrenMut<'a, '_> {
ChildrenMut(self)
}
#[must_use]
pub const fn name(&self) -> &Bytes<'a> {
&self.name
}
#[must_use]
pub const fn attributes(&self) -> &Attributes<'a> {
&self.attributes
}
pub const fn attributes_mut(&mut self) -> &mut Attributes<'a> {
&mut self.attributes
}
#[must_use]
pub const fn raw(&self) -> &Bytes<'a> {
&self.raw
}
#[must_use]
pub fn boundaries(&self, parser: &Parser<'a>) -> (usize, usize) {
let offset = self.raw.as_ptr() as usize - parser.source.as_ptr() as usize;
(offset, offset + self.raw.as_bytes().len() - 1)
}
#[must_use]
pub fn inner_text<'p>(&self, parser: &'p Parser<'a>) -> Cow<'p, str> {
let mut text = String::new();
for node in &parser.tags[self.id as usize + 1..self.subtree_end as usize] {
if let Node::Raw(bytes) = node {
text.push_str(&bytes.as_utf8_str());
}
}
Cow::Owned(text)
}
}
pub struct Children<'a, 'b>(&'b HTMLTag<'a>);
impl<'a, 'b> Children<'a, 'b> {
#[must_use]
pub const fn top(&self) -> &'b RawChildren {
&self.0.children
}
#[must_use]
pub fn all(&self, parser: &'b Parser<'a>) -> &'b [Node<'a>] {
&parser.tags[self.0.id as usize + 1..self.0.subtree_end as usize]
}
}
#[cfg(test)]
pub(crate) struct ChildrenMut<'a, 'b>(&'b mut HTMLTag<'a>);
#[cfg(test)]
impl ChildrenMut<'_, '_> {
pub(crate) const fn top_mut(&mut self) -> &mut RawChildren {
&mut self.0.children
}
}
#[derive(Debug, Clone)]
pub enum Node<'a> {
Tag(HTMLTag<'a>),
Raw(Bytes<'a>),
Comment(Bytes<'a>),
}
impl<'a> Node<'a> {
#[must_use]
pub fn inner_text<'s, 'p: 's>(&'s self, parser: &'p Parser<'a>) -> Cow<'s, str> {
match self {
Node::Tag(tag) => tag.inner_text(parser),
Node::Raw(bytes) => bytes.as_utf8_str(),
Node::Comment(_) => Cow::Borrowed(""),
}
}
#[must_use]
pub const fn children(&self) -> Option<Children<'a, '_>> {
match self {
Node::Tag(tag) => Some(tag.children()),
_ => None,
}
}
#[must_use]
pub const fn as_tag(&self) -> Option<&HTMLTag<'a>> {
match self {
Node::Tag(tag) => Some(tag),
_ => None,
}
}
pub const fn as_tag_mut(&mut self) -> Option<&mut HTMLTag<'a>> {
match self {
Node::Tag(tag) => Some(tag),
_ => None,
}
}
#[must_use]
pub const fn as_comment(&self) -> Option<&Bytes<'a>> {
match self {
Node::Comment(bytes) => Some(bytes),
_ => None,
}
}
#[must_use]
pub const fn as_raw(&self) -> Option<&Bytes<'a>> {
match self {
Node::Raw(bytes) => Some(bytes),
_ => None,
}
}
pub const fn as_raw_mut(&mut self) -> Option<&mut Bytes<'a>> {
match self {
Node::Raw(bytes) => Some(bytes),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Parser<'a> {
pub(crate) tags: Vec<Node<'a>>,
pub(crate) ast: Vec<NodeHandle>,
source: &'a str,
}
impl<'a> Parser<'a> {
#[must_use]
pub fn resolve_node_id(&self, id: u32) -> Option<&Node<'a>> {
self.tags.get(id as usize)
}
fn tag_mut(&mut self, id: u32) -> &mut HTMLTag<'a> {
match &mut self.tags[id as usize] {
Node::Tag(tag) => tag,
_ => unreachable!("the open stack holds tags"),
}
}
fn append(&mut self, node: Node<'a>, parent: Option<u32>) -> u32 {
let id = self.tags.len() as u32;
self.tags.push(node);
match parent {
Some(parent) => self.tag_mut(parent).children.push(NodeHandle(id)),
None => self.ast.push(NodeHandle(id)),
}
id
}
fn slice(&self, start: usize, end: usize) -> Bytes<'a> {
Bytes(Cow::Borrowed(&self.source.as_bytes()[start..end]))
}
}
#[derive(Debug, Clone)]
pub struct VDom<'a> {
parser: Parser<'a>,
}
impl<'a> VDom<'a> {
#[must_use]
pub const fn parser(&self) -> &Parser<'a> {
&self.parser
}
pub const fn parser_mut(&mut self) -> &mut Parser<'a> {
&mut self.parser
}
pub(crate) fn apply_data_as(&mut self, elements: Option<&[String]>) {
match elements {
Some(elements) => apply_data_as(&mut self.parser, elements),
None => apply_data_as(&mut self.parser, &DEFAULT_DATA_AS_ELEMENTS),
}
}
#[must_use]
pub fn nodes(&self) -> &[Node<'a>] {
&self.parser.tags
}
pub fn nodes_mut(&mut self) -> &mut [Node<'a>] {
&mut self.parser.tags
}
#[must_use]
pub fn children(&self) -> &[NodeHandle] {
&self.parser.ast
}
#[must_use]
pub fn query_selector<'b>(
&'b self,
selector: &'b str,
) -> Option<queryselector::QuerySelectorIterator<'a, 'b, Self>> {
let selector = queryselector::Parser::new(selector.as_bytes()).selector()?;
Some(queryselector::QuerySelectorIterator::new(selector, &self.parser, self))
}
}
#[derive(Default)]
struct Scopes {
open: Vec<u32>,
rereading: bool,
}
impl Scopes {
fn close_top(&mut self, end: u32, parser: &mut Parser<'_>) -> Option<u32> {
let id = self.open.pop()?;
parser.tag_mut(id).subtree_end = end;
Some(id)
}
fn top_is(&self, parser: &Parser<'_>, name: &[u8]) -> bool {
let top = self.open.last().and_then(|id| parser.tags[*id as usize].as_tag());
top.is_some_and(|tag| tag.name.as_bytes().eq_ignore_ascii_case(name))
}
fn in_svg(&self, parser: &Parser<'_>) -> bool {
let names = self
.open
.iter()
.rev()
.filter_map(|id| parser.tags[*id as usize].as_tag());
for tag in names {
match tag.name.as_bytes() {
b"svg" => return true,
b"foreignObject" | b"desc" | b"title" => return false,
_ => {}
}
}
false
}
}
const SVG_ELEMENTS: [(&str, &str); 37] = [
("altglyph", "altGlyph"),
("altglyphdef", "altGlyphDef"),
("altglyphitem", "altGlyphItem"),
("animatecolor", "animateColor"),
("animatemotion", "animateMotion"),
("animatetransform", "animateTransform"),
("clippath", "clipPath"),
("feblend", "feBlend"),
("fecolormatrix", "feColorMatrix"),
("fecomponenttransfer", "feComponentTransfer"),
("fecomposite", "feComposite"),
("feconvolvematrix", "feConvolveMatrix"),
("fediffuselighting", "feDiffuseLighting"),
("fedisplacementmap", "feDisplacementMap"),
("fedistantlight", "feDistantLight"),
("fedropshadow", "feDropShadow"),
("feflood", "feFlood"),
("fefunca", "feFuncA"),
("fefuncb", "feFuncB"),
("fefuncg", "feFuncG"),
("fefuncr", "feFuncR"),
("fegaussianblur", "feGaussianBlur"),
("feimage", "feImage"),
("femerge", "feMerge"),
("femergenode", "feMergeNode"),
("femorphology", "feMorphology"),
("feoffset", "feOffset"),
("fepointlight", "fePointLight"),
("fespecularlighting", "feSpecularLighting"),
("fespotlight", "feSpotLight"),
("fetile", "feTile"),
("feturbulence", "feTurbulence"),
("foreignobject", "foreignObject"),
("glyphref", "glyphRef"),
("lineargradient", "linearGradient"),
("radialgradient", "radialGradient"),
("textpath", "textPath"),
];
fn element_name<'a>(parser: &Parser<'a>, scopes: &Scopes, name: Cow<'a, str>) -> Bytes<'a> {
let svg_name = SVG_ELEMENTS
.iter()
.find(|(lower, _)| *lower == name)
.map(|(_, mixed)| *mixed);
match svg_name {
Some(mixed) if scopes.in_svg(parser) => Bytes::from(mixed),
_ => match name {
Cow::Borrowed(name) => Bytes::from(name),
Cow::Owned(name) => Bytes(Cow::Owned(name.into_bytes())),
},
}
}
fn attributes_of(list: Vec<astral_html::Attribute<'_>>) -> Attributes<'_> {
let raw = list
.into_iter()
.map(|attribute| {
let key = match attribute.name {
Cow::Borrowed(name) => Bytes::from(name),
Cow::Owned(name) => Bytes(Cow::Owned(name.into_bytes())),
};
(key, attribute.raw_value.map(Bytes::from))
})
.collect();
Attributes { raw }
}
fn start_tag<'a>(parser: &mut Parser<'a>, scopes: &mut Scopes, tag: astral_html::Tag<'a>, start: usize, end: usize) {
let closed = tag.self_closing || VOID.contains(&tag.name.as_ref());
let node = HTMLTag {
name: element_name(parser, scopes, tag.name),
attributes: attributes_of(tag.attributes),
children: RawChildren::new(),
raw: parser.slice(start, end),
id: parser.tags.len() as u32,
subtree_end: parser.tags.len() as u32 + 1,
};
let parent = scopes.open.last().copied();
let id = parser.append(Node::Tag(node), parent);
if !closed {
scopes.open.push(id);
}
}
fn end_tag(parser: &mut Parser<'_>, scopes: &mut Scopes, name: &str, end: usize) {
let closes = scopes.open.last().is_some_and(|id| match &parser.tags[*id as usize] {
Node::Tag(tag) => tag.name.as_bytes().eq_ignore_ascii_case(name.as_bytes()),
_ => false,
});
if !closes {
return;
}
let subtree_end = parser.tags.len() as u32;
if let Some(id) = scopes.close_top(subtree_end, parser) {
let start = parser.tag_mut(id).raw.as_ptr() as usize - parser.source.as_ptr() as usize;
let raw = parser.slice(start, end);
parser.tag_mut(id).raw = raw;
}
}
fn flush_text(parser: &mut Parser<'_>, scopes: &mut Scopes, text: &mut Option<(usize, usize)>) {
let Some((from, to)) = text.take() else { return };
let reread = [b"noframes".as_slice(), b"noembed", b"plaintext", b"xmp"];
if !scopes.rereading && reread.iter().any(|name| scopes.top_is(parser, name)) {
scopes.rereading = true;
let mut tokens = astral_html::Tokenizer::new(&parser.source[from..to]);
read_region(parser, scopes, &mut tokens, from);
scopes.rereading = false;
return;
}
let bytes = parser.slice(from, to);
let parent = scopes.open.last().copied();
parser.append(Node::Raw(bytes), parent);
}
trait Tokens<'a> {
fn next_token(&mut self) -> Option<astral_html::Token<'a>>;
fn offset(&self) -> usize;
}
impl<'a> Tokens<'a> for astral_html::Reader<'a> {
fn next_token(&mut self) -> Option<astral_html::Token<'a>> {
self.next()
}
fn offset(&self) -> usize {
self.position()
}
}
impl<'a> Tokens<'a> for astral_html::Tokenizer<'a> {
fn next_token(&mut self) -> Option<astral_html::Token<'a>> {
self.next()
}
fn offset(&self) -> usize {
self.position()
}
}
fn token_start(source: &str, token: &astral_html::Token<'_>, start: usize, end: usize) -> usize {
let consumed = &source[start..end];
let data = consumed.trim_start_matches("</>");
if data.len() == consumed.len() {
return start;
}
if let astral_html::Token::Text(value) = token
&& value.starts_with("</>")
&& astral_html::decode(data, false) != *value
{
return start;
}
end - data.len()
}
fn read_region<'a>(parser: &mut Parser<'a>, scopes: &mut Scopes, tokens: &mut impl Tokens<'a>, base: usize) {
let input = parser.source;
let mut start = base;
let mut text: Option<(usize, usize)> = None;
while let Some(token) = tokens.next_token() {
let end = base + tokens.offset();
let actual_start = token_start(input, &token, start, end);
if matches!(token, astral_html::Token::Text(_)) {
if actual_start != start {
flush_text(parser, scopes, &mut text);
}
text = Some((text.map_or(actual_start, |(from, _)| from), end));
start = end;
continue;
}
flush_text(parser, scopes, &mut text);
match token {
astral_html::Token::StartTag(tag) => start_tag(parser, scopes, tag, actual_start, end),
astral_html::Token::EndTag(tag) => end_tag(parser, scopes, &tag.name, end),
astral_html::Token::Comment(_) if input.as_bytes()[actual_start..].starts_with(b"<!--") => {
let bytes = parser.slice(actual_start, end);
let parent = scopes.open.last().copied();
parser.append(Node::Comment(bytes), parent);
}
_ => {}
}
start = end;
}
flush_text(parser, scopes, &mut text);
}
pub fn parse(input: &str, _options: ParserOptions) -> Result<VDom<'_>, ParseError> {
let Ok(_) = u32::try_from(input.len()) else {
return Err(ParseError::InvalidLength);
};
let mut parser = Parser {
tags: Vec::new(),
ast: Vec::new(),
source: input,
};
let mut scopes = Scopes::default();
read_region(&mut parser, &mut scopes, &mut astral_html::Reader::new(input), 0);
let subtree_end = parser.tags.len() as u32;
while scopes.close_top(subtree_end, &mut parser).is_some() {}
Ok(VDom { parser })
}
const DEFAULT_DATA_AS_ELEMENTS: [&str; 2] = ["span", "div"];
fn data_as_element(value: &str) -> Option<&'static str> {
const ELEMENTS: [&str; 13] = [
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"li",
"ul",
"ol",
"blockquote",
"pre",
"div",
];
let value = crate::text::decode_attribute_value_cow(value);
let value = value.trim_ascii();
ELEMENTS.into_iter().find(|name| value.eq_ignore_ascii_case(name))
}
fn apply_data_as<S: AsRef<str>>(parser: &mut Parser<'_>, elements: &[S]) {
if elements.is_empty() {
return;
}
for node in &mut parser.tags {
let Node::Tag(tag) = node else { continue };
let name = tag.name.as_bytes();
if !elements
.iter()
.any(|element| name.eq_ignore_ascii_case(element.as_ref().as_bytes()))
{
continue;
}
let Some(Some(value)) = tag.attributes.get("data-as") else {
continue;
};
if let Some(element) = data_as_element(&value.as_utf8_str()) {
tag.name = Bytes::from(element);
}
}
}