use std::borrow::Cow;
use std::str;
use super::kept_scripts::{ESCAPED_LT, KeptScripts, push_owner_mark};
use super::markup::{
find_html_comment_end, find_tag_end, is_json_ld_script_open_tag, matches_end_tag_start, matches_tag_start,
};
use super::structured_data::push_without_standalone_slashes;
use super::visibility::{after_bogus_comment, is_bogus_comment_marker};
fn bogus_comment_end(bytes: &[u8], idx: usize) -> Option<usize> {
let next = *bytes.get(idx + 1)?;
is_bogus_comment_marker(bytes, idx, bytes.len(), next, &bytes[idx + 2..]).then(|| after_bogus_comment(bytes, idx))
}
pub(super) fn track_svg_tag(bytes: &[u8], idx: usize, svg_depth: &mut usize) -> Option<usize> {
if matches_tag_start(bytes, idx + 1, b"svg") {
if let Some(open_end) = find_tag_end(bytes, idx + 1 + b"svg".len()) {
if !bytes[idx..open_end].ends_with(b"/>") {
*svg_depth += 1;
}
return Some(open_end);
}
} else if matches_end_tag_start(bytes, idx + 1, b"svg") {
if let Some(close_end) = find_tag_end(bytes, idx + 2 + b"svg".len()) {
if *svg_depth > 0 {
*svg_depth = svg_depth.saturating_sub(1);
}
return Some(close_end);
}
}
None
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum RawTextContent {
Removed,
RemovedUnlessStructuredData,
Kept,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Outcome {
Unchanged,
Removed,
Kept,
}
struct RawTextElement<'a> {
input: &'a str,
idx: usize,
last: usize,
name: &'a str,
content: RawTextContent,
preformatted: bool,
mark: Option<usize>,
}
fn strip_raw_text_element(
element: &RawTextElement<'_>,
tag_end: usize,
(close_start, close_idx): (usize, usize),
output: &mut Option<String>,
) -> Outcome {
let bytes = element.input.as_bytes();
let name = element.name.as_bytes();
let body = &element.input[tag_end..close_start];
let kept = match element.content {
RawTextContent::Removed => false,
RawTextContent::RemovedUnlessStructuredData => is_json_ld_script_open_tag(&element.input[element.idx..tag_end]),
RawTextContent::Kept if !body.contains('<') => return Outcome::Unchanged,
RawTextContent::Kept => true,
};
let out = output.get_or_insert_with(|| String::with_capacity(element.input.len()));
out.push_str(&element.input[element.last..element.idx]);
if kept {
let attributes = &element.input[element.idx + 1 + name.len()..tag_end];
push_kept_element(out, element.name, element.mark, attributes, body);
return Outcome::Kept;
}
if element.content == RawTextContent::Removed
&& !element.preformatted
&& element.idx > 0
&& close_idx < bytes.len()
&& !bytes[element.idx - 1].is_ascii_whitespace()
&& !bytes[close_idx].is_ascii_whitespace()
{
out.push(' ');
}
Outcome::Removed
}
fn push_kept_element(out: &mut String, name: &str, mark: Option<usize>, attributes: &str, body: &str) {
out.push('<');
out.push_str(name);
push_kept_attributes(out, mark, attributes);
let mut rest = body;
while let Some(at) = memchr::memchr(b'<', rest.as_bytes()) {
out.push_str(&rest[..at]);
out.push_str(ESCAPED_LT);
rest = &rest[at + 1..];
}
out.push_str(rest);
out.push_str("</");
out.push_str(name);
out.push('>');
}
fn push_kept_attributes(out: &mut String, mark: Option<usize>, attributes: &str) {
if let Some(mark) = mark {
push_owner_mark(out, mark);
}
let attributes = match attributes.as_bytes().first() {
Some(b'/' | b'\x0C') => {
out.push(' ');
&attributes[1..]
}
_ => attributes,
};
push_without_standalone_slashes(out, attributes);
}
const FIRST_PASS_ELEMENTS: [(&str, RawTextContent); 3] = [
("script", RawTextContent::RemovedUnlessStructuredData),
("style", RawTextContent::Removed),
("textarea", RawTextContent::Kept),
];
pub(super) fn removed_element_name(slot: usize) -> Option<&'static str> {
let (name, content) = FIRST_PASS_ELEMENTS[slot];
(content != RawTextContent::Kept).then_some(name)
}
pub fn strip_script_and_style_tags(input: &str) -> Cow<'_, str> {
FirstPass::new(input, |_| {}).run().0
}
pub fn strip_script_and_style_tags_with_kept_scripts(input: &str) -> (Cow<'_, str>, KeptScripts) {
#[cfg(feature = "metadata")]
let kept_scripts = KeptScripts::with_marks();
#[cfg(not(feature = "metadata"))]
let kept_scripts = KeptScripts::new();
FirstPass::with_kept_scripts(input, kept_scripts, |_| {}).run()
}
#[cfg(feature = "metadata")]
pub fn strip_script_and_style_tags_for_second_pass(
input: &str,
kept_scripts: KeptScripts,
) -> (Cow<'_, str>, KeptScripts) {
FirstPass::with_kept_scripts(input, kept_scripts, |_| {}).run()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PassRead {
Markup,
EndTagSearch,
CommentEndSearch,
TagRead(usize),
TagStops(usize),
}
pub(super) struct PageReads<C: FnMut(PassRead)> {
comments_never_end: bool,
tags_never_end: bool,
no_end_tag: [bool; FIRST_PASS_ELEMENTS.len()],
count: C,
}
impl<C: FnMut(PassRead)> PageReads<C> {
pub(super) const fn new(count: C) -> Self {
Self {
comments_never_end: false,
tags_never_end: false,
no_end_tag: [false; FIRST_PASS_ELEMENTS.len()],
count,
}
}
pub(super) fn raw_text_end_tag(&mut self, bytes: &[u8], from: usize, slot: usize) -> Option<(usize, usize)> {
if self.no_end_tag[slot] {
return None;
}
self.count(PassRead::EndTagSearch);
let found = find_raw_text_end_tag(bytes, from, FIRST_PASS_ELEMENTS[slot].0.as_bytes());
self.no_end_tag[slot] = found.is_none() && bytes.len() - from <= MAX_CLOSING_TAG_SCAN;
found
}
pub(super) fn count(&mut self, read: PassRead) {
(self.count)(read);
}
pub(super) fn comment_end(&mut self, bytes: &[u8], idx: usize) -> Option<usize> {
if self.comments_never_end || !bytes[idx..].starts_with(COMMENT_OPEN) {
return None;
}
self.count(PassRead::CommentEndSearch);
let from = idx + 2;
let found = find_html_comment_end(bytes, from);
self.comments_never_end = found.is_none();
found
}
pub(super) fn tag_end(&mut self, bytes: &[u8], idx: usize) -> Option<usize> {
if !opens_a_tag(bytes, idx) {
return None;
}
self.tag_end_from(bytes, idx + 1, None)
}
pub(super) fn raw_text_start_tag_end(&mut self, bytes: &[u8], lt: usize) -> Option<(usize, usize)> {
let (slot, after_name) = FIRST_PASS_ELEMENTS.iter().enumerate().find_map(|(slot, (name, _))| {
let after_name = raw_text_tag_name_end(bytes, lt, name.as_bytes(), TagSide::Start)?;
Some((slot, after_name))
})?;
let tag_end = self.tag_end_from(bytes, after_name, Some(after_name))?;
Some((slot, tag_end))
}
fn tag_end_from(&mut self, bytes: &[u8], from: usize, attributes: Option<usize>) -> Option<usize> {
if !self.tags_never_end {
let mut stops = 0;
let whole = whole_tag_end(bytes, from, attributes, &mut stops);
self.count(PassRead::TagRead(whole.unwrap_or(bytes.len()) - from));
self.count(PassRead::TagStops(stops));
self.tags_never_end = whole.is_none();
if whole.is_some() {
return whole;
}
}
memchr::memchr(b'>', &bytes[from..]).map(|offset| from + offset + 1)
}
}
pub(super) struct FirstPass<'a, C: FnMut(PassRead)> {
input: &'a str,
last: usize,
output: Option<String>,
svg_depth: usize,
pre_depth: usize,
reads: PageReads<C>,
kept_scripts: KeptScripts,
}
impl<'a, C: FnMut(PassRead)> FirstPass<'a, C> {
pub(super) const fn new(input: &'a str, count: C) -> Self {
Self::with_kept_scripts(input, KeptScripts::new(), count)
}
const fn with_kept_scripts(input: &'a str, kept_scripts: KeptScripts, count: C) -> Self {
Self {
input,
last: 0,
output: None,
svg_depth: 0,
pre_depth: 0,
reads: PageReads::new(count),
kept_scripts,
}
}
pub(super) fn run(mut self) -> (Cow<'a, str>, KeptScripts) {
let bytes = self.input.as_bytes();
let last_gt = memchr::memrchr(b'>', bytes).unwrap_or(0);
let mut idx = 0;
while idx < last_gt {
let Some(offset) = memchr::memchr(b'<', &bytes[idx..last_gt]) else {
break;
};
idx = self.read_markup(idx + offset);
}
let page = match self.output {
Some(mut out) => {
out.push_str(&self.input[self.last..]);
Cow::Owned(out)
}
None => Cow::Borrowed(self.input),
};
(page, self.kept_scripts)
}
fn read_markup(&mut self, idx: usize) -> usize {
let bytes = self.input.as_bytes();
self.reads.count(PassRead::Markup);
if let Some(after_tag) = track_svg_tag(bytes, idx, &mut self.svg_depth) {
return after_tag;
}
if self.svg_depth > 0 {
return idx + 1;
}
if bytes[idx..].starts_with(COMMENT_OPEN) {
return self.reads.comment_end(bytes, idx).unwrap_or(idx + 1);
}
if let Some(after_comment) = bogus_comment_end(bytes, idx) {
return after_comment;
}
if let Some((slot, tag_end)) = self.reads.raw_text_start_tag_end(bytes, idx) {
return self.read_raw_text_element(idx, slot, tag_end);
}
if matches_tag_start(bytes, idx + 1, b"pre") {
self.pre_depth += 1;
} else if matches_end_tag_start(bytes, idx + 1, b"pre") {
self.pre_depth = self.pre_depth.saturating_sub(1);
}
self.reads.tag_end(bytes, idx).unwrap_or(idx + 1)
}
fn read_raw_text_element(&mut self, idx: usize, slot: usize, tag_end: usize) -> usize {
let bytes = self.input.as_bytes();
let (name, content) = FIRST_PASS_ELEMENTS[slot];
let Some(close) = self.reads.raw_text_end_tag(bytes, tag_end, slot) else {
#[cfg(feature = "metadata")]
self.mark_script_with_no_end_tag(idx, tag_end, name, content);
return tag_end;
};
let element = RawTextElement {
input: self.input,
idx,
last: self.last,
name,
content,
preformatted: self.pre_depth != 0,
mark: None,
};
#[cfg(feature = "metadata")]
let element = RawTextElement {
mark: self.owner_mark(&element, tag_end, close.0),
..element
};
let outcome = strip_raw_text_element(&element, tag_end, close, &mut self.output);
if outcome != Outcome::Unchanged {
self.last = close.1;
}
close.1
}
#[cfg(feature = "metadata")]
fn owner_mark(&mut self, element: &RawTextElement<'_>, tag_end: usize, body_end: usize) -> Option<usize> {
let is_kept_script = element.content == RawTextContent::RemovedUnlessStructuredData
&& self.kept_scripts.marks
&& is_json_ld_script_open_tag(&self.input[element.idx..tag_end]);
if !is_kept_script {
return None;
}
self.kept_scripts.mark(self.input, &self.input[tag_end..body_end])
}
#[cfg(feature = "metadata")]
fn mark_script_with_no_end_tag(&mut self, idx: usize, tag_end: usize, name: &str, content: RawTextContent) {
let input = self.input;
if content != RawTextContent::RemovedUnlessStructuredData
|| self.kept_scripts.has_no_end_tag
|| !is_json_ld_script_open_tag(&input[idx..tag_end])
{
return;
}
self.kept_scripts.has_no_end_tag = true;
let Some(mark) = self.kept_scripts.mark(input, &input[tag_end..]) else {
return;
};
let after_name = idx + 1 + name.len();
let out = self.output.get_or_insert_with(|| String::with_capacity(input.len()));
out.push_str(&input[self.last..after_name]);
push_kept_attributes(out, Some(mark), &input[after_name..tag_end]);
self.last = tag_end;
}
}
pub(super) const MAX_CLOSING_TAG_SCAN: usize = 100_000_000;
#[derive(Clone, Copy, PartialEq, Eq)]
enum TagSide {
Start,
End,
}
fn raw_text_start_tag_end(bytes: &[u8], lt: usize, name: &[u8]) -> Option<usize> {
let after_name = raw_text_tag_name_end(bytes, lt, name, TagSide::Start)?;
let first_bracket = || memchr::memchr(b'>', &bytes[after_name..]).map(|offset| after_name + offset + 1);
whole_tag_end(bytes, after_name, Some(after_name), &mut 0).or_else(first_bracket)
}
fn raw_text_tag_name_end(bytes: &[u8], lt: usize, name: &[u8], side: TagSide) -> Option<usize> {
if bytes.get(lt) != Some(&b'<') {
return None;
}
let name_start = match side {
TagSide::Start => lt + 1,
TagSide::End if bytes.get(lt + 1) == Some(&b'/') => lt + 2,
TagSide::End => return None,
};
let after_name = name_start + name.len();
if !bytes.get(name_start..after_name)?.eq_ignore_ascii_case(name) {
return None;
}
if !matches!(
bytes.get(after_name)?,
b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' | b'/' | b'>'
) {
return None;
}
Some(after_name)
}
pub(super) fn tag_end_from_name(bytes: &[u8], name: usize) -> Option<usize> {
whole_tag_end(bytes, name, None, &mut 0)
}
fn whole_tag_end(bytes: &[u8], from: usize, attributes: Option<usize>, stops: &mut usize) -> Option<usize> {
whole_tag_terminator(bytes, from, attributes, stops).map(|(end, _)| end)
}
pub fn tag_terminator_from_attributes(bytes: &[u8], attributes: usize) -> Option<(usize, bool)> {
whole_tag_terminator(bytes, attributes, Some(attributes), &mut 0)
}
fn whole_tag_terminator(
bytes: &[u8],
from: usize,
attributes: Option<usize>,
stops: &mut usize,
) -> Option<(usize, bool)> {
let mut idx = from;
let mut names = attributes;
loop {
*stops += 1;
idx += memchr::memchr2(b'>', b'=', bytes.get(idx..)?)?;
if bytes[idx] == b'>' {
return Some((idx + 1, idx > 0 && bytes[idx - 1] == b'/'));
}
let names_start = *names.get_or_insert_with(|| tag_name_end(bytes, from));
if !ends_an_attribute_name(bytes, names_start, idx) {
idx += 1;
continue;
}
let after_equals = &bytes[idx + 1..];
let value = idx + 1 + after_equals.iter().position(|byte| !is_tag_white_space(*byte))?;
idx = match bytes[value] {
b'>' => return Some((value + 1, false)),
quote @ (b'"' | b'\'') => value + 2 + memchr::memchr(quote, &bytes[value + 1..])?,
_ => value + bytes[value..].iter().copied().position(ends_an_unquoted_value)?,
};
if bytes.get(idx) == Some(&b'>') {
return Some((idx + 1, false));
}
names = Some(idx);
}
}
fn tag_name_end(bytes: &[u8], from: usize) -> usize {
let name = from + usize::from(bytes.get(from) == Some(&b'/'));
bytes
.get(name..)
.and_then(|rest| rest.iter().position(|byte| ends_a_tag_name(*byte)))
.map_or(bytes.len(), |offset| name + offset)
}
fn ends_an_attribute_name(bytes: &[u8], names: usize, equals: usize) -> bool {
bytes
.get(names..equals)
.and_then(|before| before.iter().rev().find(|byte| !is_tag_white_space(**byte)))
.is_some_and(|last| *last != b'/')
}
const fn ends_a_tag_name(byte: u8) -> bool {
is_tag_white_space(byte) || matches!(byte, b'/' | b'>')
}
const fn is_tag_white_space(byte: u8) -> bool {
matches!(byte, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
}
const fn ends_an_unquoted_value(byte: u8) -> bool {
is_tag_white_space(byte) || byte == b'>'
}
#[inline]
pub fn find_closing_tag_bytes(bytes: &[u8], start: usize, tag: &[u8]) -> Option<usize> {
find_raw_text_end_tag(bytes, start, tag).map(|(_, end)| end)
}
pub fn find_raw_text_end_tag(bytes: &[u8], start: usize, name: &[u8]) -> Option<(usize, usize)> {
let mut idx = start;
while idx < bytes.len() && (idx - start) < MAX_CLOSING_TAG_SCAN {
idx += memchr::memchr(b'<', &bytes[idx..])?;
if let Some(after_name) = raw_text_tag_name_end(bytes, idx, name, TagSide::End) {
let end = after_name + memchr::memchr(b'>', &bytes[after_name..])? + 1;
return Some((idx, end));
}
idx += 1;
}
None
}
const VOID_ELEMENT_NAMES: [&[u8]; 4] = [b"br", b"hr", b"img", b"input"];
#[inline]
pub(super) fn is_self_closing_tag(tag_slice: &[u8], tag_name: &[u8]) -> bool {
tag_slice.ends_with(b"/>")
|| VOID_ELEMENT_NAMES
.iter()
.any(|void_name| tag_name.eq_ignore_ascii_case(void_name))
}
const COMMENT_OPEN: &[u8] = b"<!--";
const CDATA_OPEN: &[u8] = b"<![CDATA[";
const CDATA_CLOSE: &[u8] = b"]]>";
const RAW_TEXT_ELEMENT_NAMES: [&[u8]; 3] = [b"script", b"style", b"textarea"];
#[inline]
fn find_sequence_end(bytes: &[u8], from: usize, terminator: &[u8]) -> usize {
let len = bytes.len();
if from >= len {
return len;
}
match bytes[from..].windows(terminator.len()).position(|w| w == terminator) {
Some(offset) => from + offset + terminator.len(),
None => len,
}
}
#[inline]
pub fn skip_opaque_region(bytes: &[u8], idx: usize) -> Option<usize> {
let len = bytes.len();
if idx >= len || bytes[idx] != b'<' {
return None;
}
if bytes[idx..].starts_with(COMMENT_OPEN) {
return Some(find_html_comment_end(bytes, idx + COMMENT_OPEN.len()).unwrap_or(len));
}
if bytes[idx..].starts_with(CDATA_OPEN) {
return Some(find_sequence_end(bytes, idx + CDATA_OPEN.len(), CDATA_CLOSE));
}
for raw_text_name in RAW_TEXT_ELEMENT_NAMES {
if let Some(open_end) = raw_text_start_tag_end(bytes, idx, raw_text_name) {
return Some(find_closing_tag_bytes(bytes, open_end, raw_text_name).unwrap_or(len));
}
}
None
}
#[inline]
pub(super) fn opens_a_tag(bytes: &[u8], idx: usize) -> bool {
match bytes.get(idx + 1) {
Some(b'/' | b'!') => bytes.get(idx + 2).is_some_and(u8::is_ascii_alphabetic),
Some(byte) => byte.is_ascii_alphabetic(),
None => false,
}
}
#[inline]
pub fn find_closing_tag_bytes_nested(bytes: &[u8], start: usize, tag: &[u8]) -> Option<usize> {
let len = bytes.len();
if tag.is_empty() {
return None;
}
let mut idx = start;
let mut depth = 1usize;
while idx < len && (idx - start) < MAX_CLOSING_TAG_SCAN {
if bytes[idx] != b'<' {
match memchr::memchr(b'<', &bytes[idx..]) {
Some(pos) => idx += pos,
None => break,
}
}
if let Some(region_end) = skip_opaque_region(bytes, idx) {
idx = region_end;
continue;
}
if matches_end_tag_start(bytes, idx + 1, tag) {
if let Some(close_end) = find_tag_end(bytes, idx + 2 + tag.len()) {
depth -= 1;
if depth == 0 {
return Some(close_end);
}
idx = close_end;
continue;
}
} else if matches_tag_start(bytes, idx + 1, tag) {
if let Some(open_end) = find_tag_end(bytes, idx + 1 + tag.len()) {
if !is_self_closing_tag(&bytes[idx..open_end], tag) {
depth += 1;
}
idx = open_end;
continue;
}
} else if opens_a_tag(bytes, idx) {
if let Some(unrelated_tag_end) = find_tag_end(bytes, idx + 1) {
idx = unrelated_tag_end;
continue;
}
}
idx += 1;
}
None
}
pub(super) fn matching_tag_ends(bytes: &[u8]) -> ahash::AHashMap<usize, Option<usize>> {
let mut stacks: ahash::AHashMap<Vec<u8>, Vec<usize>> = ahash::AHashMap::new();
let mut ends = ahash::AHashMap::new();
let mut idx = 0;
let last_gt = bytes.iter().rposition(|&byte| byte == b'>').unwrap_or(0);
while idx < last_gt {
let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) else {
break;
};
idx += offset;
if let Some(end) = skip_opaque_region(bytes, idx) {
idx = end;
continue;
}
if !opens_a_tag(bytes, idx) {
idx += 1;
continue;
}
let closing = bytes.get(idx + 1) == Some(&b'/');
let start = idx + if closing { 2 } else { 1 };
let name_len = bytes[start..]
.iter()
.take_while(|byte| !byte.is_ascii_whitespace() && !matches!(byte, b'>' | b'/'))
.count();
let name = bytes[start..start + name_len].to_ascii_lowercase();
let Some(end) = find_tag_end(bytes, start + name_len) else {
break;
};
let stack = stacks.entry(name.clone()).or_default();
if closing {
if let Some(open) = stack.pop() {
ends.insert(open, Some(end));
}
} else if !is_self_closing_tag(&bytes[idx..end], &name) {
ends.insert(idx, None);
stack.push(idx);
}
idx = end;
}
ends
}