1use std::borrow::Cow;
4
5pub mod queryselector;
7mod stream;
8mod util;
9pub use queryselector::Selector;
10
11pub type InnerNodeHandle = u32;
13
14const VOID: [&str; 15] = [
15 "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track",
16 "wbr",
17];
18
19#[derive(Debug, Clone, Default, Eq)]
21pub struct Bytes<'a>(Cow<'a, [u8]>);
22
23#[derive(Debug)]
25pub enum SetBytesError {
26 LengthOverflow,
28}
29
30impl Bytes<'_> {
31 #[must_use]
33 pub fn new() -> Self {
34 Self::default()
35 }
36 #[must_use]
38 pub fn as_utf8_str(&self) -> Cow<'_, str> {
39 String::from_utf8_lossy(&self.0)
40 }
41 #[must_use]
43 pub fn try_as_utf8_str(&self) -> Option<&str> {
44 std::str::from_utf8(&self.0).ok()
45 }
46 #[must_use]
48 pub fn as_bytes(&self) -> &[u8] {
49 &self.0
50 }
51 #[must_use]
53 pub fn as_ptr(&self) -> *const u8 {
54 self.0.as_ptr()
55 }
56 pub fn set<B: Into<Vec<u8>>>(&mut self, data: B) -> Result<Option<Box<[u8]>>, SetBytesError> {
58 self.0 = Cow::Owned(data.into());
59 Ok(None)
60 }
61}
62
63impl std::hash::Hash for Bytes<'_> {
64 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
65 self.0.hash(state);
66 }
67}
68impl PartialEq for Bytes<'_> {
69 fn eq(&self, other: &Self) -> bool {
70 self.0 == other.0
71 }
72}
73impl PartialEq<str> for Bytes<'_> {
74 fn eq(&self, other: &str) -> bool {
75 self.as_bytes() == other.as_bytes()
76 }
77}
78impl PartialEq<&str> for Bytes<'_> {
79 fn eq(&self, other: &&str) -> bool {
80 self.as_bytes() == other.as_bytes()
81 }
82}
83impl PartialEq<[u8]> for Bytes<'_> {
84 fn eq(&self, other: &[u8]) -> bool {
85 self.as_bytes() == other
86 }
87}
88impl PartialEq<&[u8]> for Bytes<'_> {
89 fn eq(&self, other: &&[u8]) -> bool {
90 self.as_bytes() == *other
91 }
92}
93impl<'a> From<&'a str> for Bytes<'a> {
94 fn from(value: &'a str) -> Self {
95 Self(Cow::Borrowed(value.as_bytes()))
96 }
97}
98impl<'a> From<&'a [u8]> for Bytes<'a> {
99 fn from(value: &'a [u8]) -> Self {
100 Self(Cow::Borrowed(value))
101 }
102}
103impl TryFrom<String> for Bytes<'static> {
104 type Error = SetBytesError;
105 fn try_from(value: String) -> Result<Self, Self::Error> {
106 Ok(Self(Cow::Owned(value.into_bytes())))
107 }
108}
109
110#[derive(Debug, Clone, Copy, Default)]
112pub struct ParserOptions;
113impl ParserOptions {
114 #[must_use]
116 pub const fn new() -> Self {
117 Self
118 }
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum ParseError {
124 InvalidLength,
126}
127impl std::fmt::Display for ParseError {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 f.write_str("the input length exceeds the capacity of the parser")
130 }
131}
132impl std::error::Error for ParseError {}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
136pub struct NodeHandle(u32);
137impl NodeHandle {
138 #[must_use]
140 pub const fn new(node: u32) -> Self {
141 Self(node)
142 }
143 #[must_use]
145 pub fn get<'p, 'buf>(&self, parser: &'p Parser<'buf>) -> Option<&'p Node<'buf>> {
146 parser.tags.get(self.0 as usize)
147 }
148 pub fn get_mut<'p, 'buf>(&self, parser: &'p mut Parser<'buf>) -> Option<&'p mut Node<'buf>> {
150 parser.tags.get_mut(self.0 as usize)
151 }
152 #[must_use]
154 pub const fn get_inner(&self) -> u32 {
155 self.0
156 }
157}
158
159pub type RawChildren = smallvec::SmallVec<[NodeHandle; 4]>;
161
162#[derive(Debug, Clone, Default)]
164pub struct Attributes<'a> {
165 raw: Vec<(Bytes<'a>, Option<Bytes<'a>>)>,
166}
167
168impl<'a> Attributes<'a> {
169 #[must_use]
171 pub const fn len(&self) -> usize {
172 self.raw.len()
173 }
174 #[must_use]
176 pub const fn is_empty(&self) -> bool {
177 self.raw.is_empty()
178 }
179 pub fn get<B: Into<Bytes<'a>>>(&self, key: B) -> Option<Option<&Bytes<'a>>> {
181 let key = key.into();
182 self.raw
183 .iter()
184 .find(|(name, _)| *name == key)
185 .map(|(_, value)| value.as_ref())
186 }
187 pub fn contains<B: Into<Bytes<'a>>>(&self, key: B) -> bool {
189 self.get(key).is_some()
190 }
191 pub fn remove<B: Into<Bytes<'a>>>(&mut self, key: B) -> Option<Option<Bytes<'a>>> {
193 let key = key.into();
194 let index = self.raw.iter().position(|(name, _)| *name == key)?;
195 Some(self.raw.remove(index).1)
196 }
197 pub fn iter(&self) -> impl Iterator<Item = (Cow<'_, str>, Option<Cow<'_, str>>)> + '_ {
199 self.raw
200 .iter()
201 .map(|(name, value)| (name.as_utf8_str(), value.as_ref().map(Bytes::as_utf8_str)))
202 }
203 pub fn is_class_member<B: AsRef<[u8]>>(&self, member: B) -> bool {
205 self.class().is_some_and(|class| {
206 class
207 .as_utf8_str()
208 .split_ascii_whitespace()
209 .any(|name| name.as_bytes() == member.as_ref())
210 })
211 }
212 #[must_use]
214 pub fn id(&self) -> Option<&Bytes<'a>> {
215 self.get("id").flatten()
216 }
217 #[must_use]
219 pub fn class(&self) -> Option<&Bytes<'a>> {
220 self.get("class").flatten()
221 }
222}
223
224#[derive(Debug, Clone)]
226pub struct HTMLTag<'a> {
227 name: Bytes<'a>,
228 attributes: Attributes<'a>,
229 children: RawChildren,
230 raw: Bytes<'a>,
231 id: u32,
232 subtree_end: u32,
233}
234
235impl<'a> HTMLTag<'a> {
236 #[must_use]
238 pub const fn children(&self) -> Children<'a, '_> {
239 Children(self)
240 }
241 #[cfg(test)]
243 pub(crate) const fn children_mut(&mut self) -> ChildrenMut<'a, '_> {
244 ChildrenMut(self)
245 }
246 #[must_use]
248 pub const fn name(&self) -> &Bytes<'a> {
249 &self.name
250 }
251 #[must_use]
253 pub const fn attributes(&self) -> &Attributes<'a> {
254 &self.attributes
255 }
256 pub const fn attributes_mut(&mut self) -> &mut Attributes<'a> {
258 &mut self.attributes
259 }
260 #[must_use]
262 pub const fn raw(&self) -> &Bytes<'a> {
263 &self.raw
264 }
265 #[must_use]
267 pub fn boundaries(&self, parser: &Parser<'a>) -> (usize, usize) {
268 let offset = self.raw.as_ptr() as usize - parser.source.as_ptr() as usize;
269 (offset, offset + self.raw.as_bytes().len() - 1)
270 }
271 #[must_use]
273 pub fn inner_text<'p>(&self, parser: &'p Parser<'a>) -> Cow<'p, str> {
274 let mut text = String::new();
275 for node in &parser.tags[self.id as usize + 1..self.subtree_end as usize] {
276 if let Node::Raw(bytes) = node {
277 text.push_str(&bytes.as_utf8_str());
278 }
279 }
280 Cow::Owned(text)
281 }
282}
283
284pub struct Children<'a, 'b>(&'b HTMLTag<'a>);
286
287impl<'a, 'b> Children<'a, 'b> {
288 #[must_use]
290 pub const fn top(&self) -> &'b RawChildren {
291 &self.0.children
292 }
293 #[must_use]
295 pub fn all(&self, parser: &'b Parser<'a>) -> &'b [Node<'a>] {
296 &parser.tags[self.0.id as usize + 1..self.0.subtree_end as usize]
297 }
298}
299
300#[cfg(test)]
302pub(crate) struct ChildrenMut<'a, 'b>(&'b mut HTMLTag<'a>);
303
304#[cfg(test)]
305impl ChildrenMut<'_, '_> {
306 pub(crate) const fn top_mut(&mut self) -> &mut RawChildren {
308 &mut self.0.children
309 }
310}
311
312#[derive(Debug, Clone)]
314pub enum Node<'a> {
315 Tag(HTMLTag<'a>),
317 Raw(Bytes<'a>),
319 Comment(Bytes<'a>),
321}
322
323impl<'a> Node<'a> {
324 #[must_use]
326 pub fn inner_text<'s, 'p: 's>(&'s self, parser: &'p Parser<'a>) -> Cow<'s, str> {
327 match self {
328 Node::Tag(tag) => tag.inner_text(parser),
329 Node::Raw(bytes) => bytes.as_utf8_str(),
330 Node::Comment(_) => Cow::Borrowed(""),
331 }
332 }
333 #[must_use]
335 pub const fn children(&self) -> Option<Children<'a, '_>> {
336 match self {
337 Node::Tag(tag) => Some(tag.children()),
338 _ => None,
339 }
340 }
341 #[must_use]
343 pub const fn as_tag(&self) -> Option<&HTMLTag<'a>> {
344 match self {
345 Node::Tag(tag) => Some(tag),
346 _ => None,
347 }
348 }
349 pub const fn as_tag_mut(&mut self) -> Option<&mut HTMLTag<'a>> {
351 match self {
352 Node::Tag(tag) => Some(tag),
353 _ => None,
354 }
355 }
356 #[must_use]
358 pub const fn as_comment(&self) -> Option<&Bytes<'a>> {
359 match self {
360 Node::Comment(bytes) => Some(bytes),
361 _ => None,
362 }
363 }
364 #[must_use]
366 pub const fn as_raw(&self) -> Option<&Bytes<'a>> {
367 match self {
368 Node::Raw(bytes) => Some(bytes),
369 _ => None,
370 }
371 }
372 pub const fn as_raw_mut(&mut self) -> Option<&mut Bytes<'a>> {
374 match self {
375 Node::Raw(bytes) => Some(bytes),
376 _ => None,
377 }
378 }
379}
380
381#[derive(Debug, Clone)]
383pub struct Parser<'a> {
384 pub(crate) tags: Vec<Node<'a>>,
385 pub(crate) ast: Vec<NodeHandle>,
386 source: &'a str,
387}
388
389impl<'a> Parser<'a> {
390 #[must_use]
392 pub fn resolve_node_id(&self, id: u32) -> Option<&Node<'a>> {
393 self.tags.get(id as usize)
394 }
395
396 fn tag_mut(&mut self, id: u32) -> &mut HTMLTag<'a> {
397 match &mut self.tags[id as usize] {
398 Node::Tag(tag) => tag,
399 _ => unreachable!("the open stack holds tags"),
400 }
401 }
402
403 fn append(&mut self, node: Node<'a>, parent: Option<u32>) -> u32 {
404 let id = self.tags.len() as u32;
405 self.tags.push(node);
406 match parent {
407 Some(parent) => self.tag_mut(parent).children.push(NodeHandle(id)),
408 None => self.ast.push(NodeHandle(id)),
409 }
410 id
411 }
412
413 fn slice(&self, start: usize, end: usize) -> Bytes<'a> {
414 Bytes(Cow::Borrowed(&self.source.as_bytes()[start..end]))
415 }
416}
417
418#[derive(Debug, Clone)]
420pub struct VDom<'a> {
421 parser: Parser<'a>,
422}
423
424impl<'a> VDom<'a> {
425 #[must_use]
427 pub const fn parser(&self) -> &Parser<'a> {
428 &self.parser
429 }
430 pub const fn parser_mut(&mut self) -> &mut Parser<'a> {
432 &mut self.parser
433 }
434 pub(crate) fn apply_data_as(&mut self, elements: Option<&[String]>) {
438 match elements {
439 Some(elements) => apply_data_as(&mut self.parser, elements),
440 None => apply_data_as(&mut self.parser, &DEFAULT_DATA_AS_ELEMENTS),
441 }
442 }
443 #[must_use]
445 pub fn nodes(&self) -> &[Node<'a>] {
446 &self.parser.tags
447 }
448 pub fn nodes_mut(&mut self) -> &mut [Node<'a>] {
450 &mut self.parser.tags
451 }
452 #[must_use]
454 pub fn children(&self) -> &[NodeHandle] {
455 &self.parser.ast
456 }
457 #[must_use]
459 pub fn query_selector<'b>(
460 &'b self,
461 selector: &'b str,
462 ) -> Option<queryselector::QuerySelectorIterator<'a, 'b, Self>> {
463 let selector = queryselector::Parser::new(selector.as_bytes()).selector()?;
464 Some(queryselector::QuerySelectorIterator::new(selector, &self.parser, self))
465 }
466}
467
468#[derive(Default)]
472struct Scopes {
473 open: Vec<u32>,
474 rereading: bool,
476}
477
478impl Scopes {
479 fn close_top(&mut self, end: u32, parser: &mut Parser<'_>) -> Option<u32> {
480 let id = self.open.pop()?;
481 parser.tag_mut(id).subtree_end = end;
482 Some(id)
483 }
484
485 fn top_is(&self, parser: &Parser<'_>, name: &[u8]) -> bool {
486 let top = self.open.last().and_then(|id| parser.tags[*id as usize].as_tag());
487 top.is_some_and(|tag| tag.name.as_bytes().eq_ignore_ascii_case(name))
488 }
489
490 fn in_svg(&self, parser: &Parser<'_>) -> bool {
492 let names = self
493 .open
494 .iter()
495 .rev()
496 .filter_map(|id| parser.tags[*id as usize].as_tag());
497 for tag in names {
498 match tag.name.as_bytes() {
499 b"svg" => return true,
500 b"foreignObject" | b"desc" | b"title" => return false,
501 _ => {}
502 }
503 }
504 false
505 }
506}
507
508const SVG_ELEMENTS: [(&str, &str); 37] = [
510 ("altglyph", "altGlyph"),
511 ("altglyphdef", "altGlyphDef"),
512 ("altglyphitem", "altGlyphItem"),
513 ("animatecolor", "animateColor"),
514 ("animatemotion", "animateMotion"),
515 ("animatetransform", "animateTransform"),
516 ("clippath", "clipPath"),
517 ("feblend", "feBlend"),
518 ("fecolormatrix", "feColorMatrix"),
519 ("fecomponenttransfer", "feComponentTransfer"),
520 ("fecomposite", "feComposite"),
521 ("feconvolvematrix", "feConvolveMatrix"),
522 ("fediffuselighting", "feDiffuseLighting"),
523 ("fedisplacementmap", "feDisplacementMap"),
524 ("fedistantlight", "feDistantLight"),
525 ("fedropshadow", "feDropShadow"),
526 ("feflood", "feFlood"),
527 ("fefunca", "feFuncA"),
528 ("fefuncb", "feFuncB"),
529 ("fefuncg", "feFuncG"),
530 ("fefuncr", "feFuncR"),
531 ("fegaussianblur", "feGaussianBlur"),
532 ("feimage", "feImage"),
533 ("femerge", "feMerge"),
534 ("femergenode", "feMergeNode"),
535 ("femorphology", "feMorphology"),
536 ("feoffset", "feOffset"),
537 ("fepointlight", "fePointLight"),
538 ("fespecularlighting", "feSpecularLighting"),
539 ("fespotlight", "feSpotLight"),
540 ("fetile", "feTile"),
541 ("feturbulence", "feTurbulence"),
542 ("foreignobject", "foreignObject"),
543 ("glyphref", "glyphRef"),
544 ("lineargradient", "linearGradient"),
545 ("radialgradient", "radialGradient"),
546 ("textpath", "textPath"),
547];
548
549fn element_name<'a>(parser: &Parser<'a>, scopes: &Scopes, name: Cow<'a, str>) -> Bytes<'a> {
551 let svg_name = SVG_ELEMENTS
552 .iter()
553 .find(|(lower, _)| *lower == name)
554 .map(|(_, mixed)| *mixed);
555 match svg_name {
556 Some(mixed) if scopes.in_svg(parser) => Bytes::from(mixed),
557 _ => match name {
558 Cow::Borrowed(name) => Bytes::from(name),
559 Cow::Owned(name) => Bytes(Cow::Owned(name.into_bytes())),
560 },
561 }
562}
563
564fn attributes_of(list: Vec<astral_html::Attribute<'_>>) -> Attributes<'_> {
565 let raw = list
566 .into_iter()
567 .map(|attribute| {
568 let key = match attribute.name {
569 Cow::Borrowed(name) => Bytes::from(name),
570 Cow::Owned(name) => Bytes(Cow::Owned(name.into_bytes())),
571 };
572 (key, attribute.raw_value.map(Bytes::from))
573 })
574 .collect();
575 Attributes { raw }
576}
577
578fn start_tag<'a>(parser: &mut Parser<'a>, scopes: &mut Scopes, tag: astral_html::Tag<'a>, start: usize, end: usize) {
579 let closed = tag.self_closing || VOID.contains(&tag.name.as_ref());
580 let node = HTMLTag {
581 name: element_name(parser, scopes, tag.name),
582 attributes: attributes_of(tag.attributes),
583 children: RawChildren::new(),
584 raw: parser.slice(start, end),
585 id: parser.tags.len() as u32,
586 subtree_end: parser.tags.len() as u32 + 1,
587 };
588 let parent = scopes.open.last().copied();
589 let id = parser.append(Node::Tag(node), parent);
590 if !closed {
591 scopes.open.push(id);
592 }
593}
594
595fn end_tag(parser: &mut Parser<'_>, scopes: &mut Scopes, name: &str, end: usize) {
597 let closes = scopes.open.last().is_some_and(|id| match &parser.tags[*id as usize] {
598 Node::Tag(tag) => tag.name.as_bytes().eq_ignore_ascii_case(name.as_bytes()),
599 _ => false,
600 });
601 if !closes {
602 return;
603 }
604 let subtree_end = parser.tags.len() as u32;
605 if let Some(id) = scopes.close_top(subtree_end, parser) {
606 let start = parser.tag_mut(id).raw.as_ptr() as usize - parser.source.as_ptr() as usize;
607 let raw = parser.slice(start, end);
608 parser.tag_mut(id).raw = raw;
609 }
610}
611
612fn flush_text(parser: &mut Parser<'_>, scopes: &mut Scopes, text: &mut Option<(usize, usize)>) {
613 let Some((from, to)) = text.take() else { return };
614 let reread = [b"noframes".as_slice(), b"noembed", b"plaintext", b"xmp"];
618 if !scopes.rereading && reread.iter().any(|name| scopes.top_is(parser, name)) {
619 scopes.rereading = true;
620 let mut tokens = astral_html::Tokenizer::new(&parser.source[from..to]);
621 read_region(parser, scopes, &mut tokens, from);
622 scopes.rereading = false;
623 return;
624 }
625 let bytes = parser.slice(from, to);
626 let parent = scopes.open.last().copied();
627 parser.append(Node::Raw(bytes), parent);
628}
629
630trait Tokens<'a> {
633 fn next_token(&mut self) -> Option<astral_html::Token<'a>>;
634 fn offset(&self) -> usize;
635}
636
637impl<'a> Tokens<'a> for astral_html::Reader<'a> {
638 fn next_token(&mut self) -> Option<astral_html::Token<'a>> {
639 self.next()
640 }
641 fn offset(&self) -> usize {
642 self.position()
643 }
644}
645
646impl<'a> Tokens<'a> for astral_html::Tokenizer<'a> {
647 fn next_token(&mut self) -> Option<astral_html::Token<'a>> {
648 self.next()
649 }
650 fn offset(&self) -> usize {
651 self.position()
652 }
653}
654
655fn token_start(source: &str, token: &astral_html::Token<'_>, start: usize, end: usize) -> usize {
656 let consumed = &source[start..end];
657 let data = consumed.trim_start_matches("</>");
658 if data.len() == consumed.len() {
659 return start;
660 }
661 if let astral_html::Token::Text(value) = token
664 && value.starts_with("</>")
665 && astral_html::decode(data, false) != *value
666 {
667 return start;
668 }
669 end - data.len()
670}
671
672fn read_region<'a>(parser: &mut Parser<'a>, scopes: &mut Scopes, tokens: &mut impl Tokens<'a>, base: usize) {
673 let input = parser.source;
674 let mut start = base;
675 let mut text: Option<(usize, usize)> = None;
676 while let Some(token) = tokens.next_token() {
677 let end = base + tokens.offset();
678 let actual_start = token_start(input, &token, start, end);
679 if matches!(token, astral_html::Token::Text(_)) {
680 if actual_start != start {
681 flush_text(parser, scopes, &mut text);
682 }
683 text = Some((text.map_or(actual_start, |(from, _)| from), end));
684 start = end;
685 continue;
686 }
687 flush_text(parser, scopes, &mut text);
688 match token {
689 astral_html::Token::StartTag(tag) => start_tag(parser, scopes, tag, actual_start, end),
690 astral_html::Token::EndTag(tag) => end_tag(parser, scopes, &tag.name, end),
691 astral_html::Token::Comment(_) if input.as_bytes()[actual_start..].starts_with(b"<!--") => {
692 let bytes = parser.slice(actual_start, end);
693 let parent = scopes.open.last().copied();
694 parser.append(Node::Comment(bytes), parent);
695 }
696 _ => {}
697 }
698 start = end;
699 }
700 flush_text(parser, scopes, &mut text);
701}
702
703pub fn parse(input: &str, _options: ParserOptions) -> Result<VDom<'_>, ParseError> {
705 let Ok(_) = u32::try_from(input.len()) else {
706 return Err(ParseError::InvalidLength);
707 };
708 let mut parser = Parser {
709 tags: Vec::new(),
710 ast: Vec::new(),
711 source: input,
712 };
713 let mut scopes = Scopes::default();
714 read_region(&mut parser, &mut scopes, &mut astral_html::Reader::new(input), 0);
715 let subtree_end = parser.tags.len() as u32;
716 while scopes.close_top(subtree_end, &mut parser).is_some() {}
717 Ok(VDom { parser })
718}
719
720const DEFAULT_DATA_AS_ELEMENTS: [&str; 2] = ["span", "div"];
722
723fn data_as_element(value: &str) -> Option<&'static str> {
725 const ELEMENTS: [&str; 13] = [
726 "p",
727 "h1",
728 "h2",
729 "h3",
730 "h4",
731 "h5",
732 "h6",
733 "li",
734 "ul",
735 "ol",
736 "blockquote",
737 "pre",
738 "div",
739 ];
740 let value = crate::text::decode_attribute_value_cow(value);
741 let value = value.trim_ascii();
742 ELEMENTS.into_iter().find(|name| value.eq_ignore_ascii_case(name))
743}
744
745fn apply_data_as<S: AsRef<str>>(parser: &mut Parser<'_>, elements: &[S]) {
749 if elements.is_empty() {
750 return;
751 }
752 for node in &mut parser.tags {
753 let Node::Tag(tag) = node else { continue };
754 let name = tag.name.as_bytes();
755 if !elements
756 .iter()
757 .any(|element| name.eq_ignore_ascii_case(element.as_ref().as_bytes()))
758 {
759 continue;
760 }
761 let Some(Some(value)) = tag.attributes.get("data-as") else {
762 continue;
763 };
764 if let Some(element) = data_as_element(&value.as_utf8_str()) {
765 tag.name = Bytes::from(element);
766 }
767 }
768}