use std::borrow::Cow;
use super::head_scan::body_start;
use super::kept::{OpenKept, TagStep};
use super::markup::{find_html_comment_end, find_subslice, find_tag_end, matches_tag_start, skip_written_text_element};
use super::raw_text::{
find_closing_tag_bytes_nested, is_self_closing_tag, matching_tag_ends, opens_a_tag, skip_opaque_region,
};
use crate::options::HiddenContent;
pub fn sanitize_markdown_url(url: &str) -> Cow<'_, str> {
let Some(mid) = url.find("](") else {
return Cow::Borrowed(url);
};
if !url[..mid].contains('[') {
return Cow::Borrowed(url);
}
let paren_start = mid + 2;
let Some(rel_end) = url[paren_start..].find(')') else {
return Cow::Borrowed(url);
};
let paren_end = paren_start + rel_end;
if paren_start >= paren_end {
return Cow::Borrowed(url);
}
Cow::Owned(url[paren_start..paren_end].to_string())
}
fn skip_real_comment_or_cdata(bytes: &[u8], idx: usize, len: usize, next: u8, rest: &[u8]) -> Option<usize> {
if next == b'!' && rest.starts_with(b"--") {
return Some(find_html_comment_end(bytes, idx + 4).unwrap_or(len));
}
if next == b'!' && rest.starts_with(b"[CDATA[") {
return Some(find_subslice(bytes, idx + 9, b"]]>").map_or(len, |end| end + 3));
}
None
}
pub(super) fn is_bogus_comment_marker(bytes: &[u8], idx: usize, len: usize, next: u8, rest: &[u8]) -> bool {
if next == b'?' {
return true;
}
if next == b'!' {
return !(rest.len() >= 7 && rest[..7].eq_ignore_ascii_case(b"DOCTYPE"));
}
if next == b'/' {
return idx + 2 >= len || !bytes[idx + 2].is_ascii_alphabetic();
}
false
}
pub(super) fn after_bogus_comment(bytes: &[u8], idx: usize) -> usize {
memchr::memchr(b'>', &bytes[idx + 1..]).map_or(bytes.len(), |off| idx + 1 + off + 1)
}
fn has_bogus_comment_candidate(bytes: &[u8]) -> bool {
memchr::memchr3_iter(b'?', b'!', b'/', bytes).any(|idx| {
if idx == 0 || bytes[idx - 1] != b'<' {
return false;
}
let next = bytes[idx];
let rest = &bytes[idx + 1..];
if next == b'!' && (rest.starts_with(b"--") || rest.starts_with(b"[CDATA[")) {
return false;
}
is_bogus_comment_marker(bytes, idx - 1, bytes.len(), next, rest)
})
}
pub fn strip_bogus_comments(input: &str) -> Cow<'_, str> {
let bytes = input.as_bytes();
let len = bytes.len();
if len < 2 || !has_bogus_comment_candidate(bytes) {
return Cow::Borrowed(input);
}
let mut idx = 0;
let mut last = 0;
let mut output: Option<String> = None;
while let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) {
idx += offset;
if idx + 1 >= len {
break;
}
let next = bytes[idx + 1];
let rest = if idx + 2 <= len {
&bytes[idx + 2..]
} else {
&bytes[len..]
};
if let Some(new_idx) = skip_real_comment_or_cdata(bytes, idx, len, next, rest) {
idx = new_idx;
continue;
}
if !is_bogus_comment_marker(bytes, idx, len, next, rest) {
if next.is_ascii_alphabetic() {
idx = find_tag_end(bytes, idx + 1).unwrap_or(len);
continue;
}
idx += 1;
continue;
}
let end = after_bogus_comment(bytes, idx);
let out = output.get_or_insert_with(|| String::with_capacity(len));
out.push_str(&input[last..idx]);
last = end;
idx = end;
}
match output {
Some(mut out) => {
out.push_str(&input[last..]);
Cow::Owned(out)
}
None => Cow::Borrowed(input),
}
}
fn hidden_element_remove_end(
bytes: &[u8],
idx: usize,
tag_end: usize,
ends: &mut Option<ahash::AHashMap<usize, Option<usize>>>,
) -> usize {
let name_start = idx + 1;
let name_len = bytes[name_start..]
.iter()
.take_while(|byte| !byte.is_ascii_whitespace() && !matches!(byte, b'>' | b'/'))
.count();
let name = &bytes[name_start..name_start + name_len];
if is_self_closing_tag(&bytes[idx..tag_end], name) {
return tag_end;
}
if let Some(end) = ends.get_or_insert_with(|| matching_tag_ends(bytes)).get(&idx) {
return end.unwrap_or(tag_end);
}
find_closing_tag_bytes_nested(bytes, tag_end, name).unwrap_or(tag_end)
}
fn hidden_element_removal_end(
input: &str,
bytes: &[u8],
idx: usize,
tag_end: usize,
ends: &mut Option<ahash::AHashMap<usize, Option<usize>>>,
) -> Option<usize> {
let tag_slice = &input[idx..tag_end];
if tag_has_hidden_attribute(tag_slice) {
return Some(hidden_element_remove_end(bytes, idx, tag_end, ends));
}
match hidden_style_reason(tag_slice)? {
HiddenStyleReason::Definitive => Some(hidden_element_remove_end(bytes, idx, tag_end, ends)),
HiddenStyleReason::FontSizeZero => {
if matches_tag_start(bytes, idx + 1, b"img") {
return None;
}
let remove_end = hidden_element_remove_end(bytes, idx, tag_end, ends);
let subtree = input.get(tag_end..remove_end).unwrap_or("");
(!region_restores_visible_content(subtree)).then_some(remove_end)
}
}
}
struct TagEnds {
positions: Vec<usize>,
ends: Vec<Option<usize>>,
}
impl TagEnds {
fn new(bytes: &[u8]) -> Self {
let positions: Vec<usize> = memchr::memchr3_iter(b'"', b'\'', b'>', bytes).collect();
let mut ends = vec![None; positions.len()];
let (mut next_double, mut next_single) = (None, None);
for index in (0..positions.len()).rev() {
let position = positions[index];
let next_same: &mut Option<usize> = match bytes[position] {
b'>' => {
ends[index] = Some(position + 1);
continue;
}
b'"' => &mut next_double,
_ => &mut next_single,
};
let end_after_partner = (*next_same).and_then(|partner| ends.get(partner + 1).copied().flatten());
ends[index] = end_after_partner;
*next_same = Some(index);
}
Self { positions, ends }
}
fn tag_end(&self, from: usize) -> Option<usize> {
let index = self.positions.partition_point(|&position| position < from);
self.ends.get(index).copied().flatten()
}
}
pub(super) struct TagEndScan<'a> {
bytes: &'a [u8],
table: Option<TagEnds>,
}
impl<'a> TagEndScan<'a> {
pub(super) const fn new(bytes: &'a [u8]) -> Self {
Self { bytes, table: None }
}
pub(super) fn tag_end(&mut self, from: usize) -> Option<usize> {
if let Some(table) = &self.table {
return table.tag_end(from);
}
let tag_end = find_tag_end(self.bytes, from);
if tag_end.is_none() {
self.table = Some(TagEnds::new(self.bytes));
}
tag_end
}
}
pub fn strip_hidden_elements(input: &str) -> Cow<'_, str> {
let bytes = input.as_bytes();
let len = bytes.len();
if len == 0 || !bytes.contains(&b'<') {
return Cow::Borrowed(input);
}
if memchr::memchr2(b'h', b'H', bytes).is_none() && memchr::memchr2(b's', b'S', bytes).is_none() {
return Cow::Borrowed(input);
}
let mut tag_ends = TagEndScan::new(bytes);
let mut idx = 0;
let mut last = 0;
let mut output: Option<String> = None;
let mut ends = None;
let mut math_slots = None;
while idx < len {
let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) else {
break;
};
idx += offset;
let starts_tag_name = idx + 1 < len && bytes[idx + 1].is_ascii_alphabetic();
if !starts_tag_name {
idx += 1;
continue;
}
if let Some(tag_end) = tag_ends.tag_end(idx + 1) {
if let Some(remove_end) = hidden_element_removal_end(input, bytes, idx, tag_end, &mut ends) {
let out = output.get_or_insert_with(|| String::with_capacity(len));
out.push_str(&input[last..idx]);
let slots = math_slots.get_or_insert_with(|| crate::converter::utility::math::semantics_slots(input));
if slots.contains(&idx) {
out.push_str("<mrow></mrow>");
}
last = remove_end;
idx = remove_end;
continue;
}
idx = tag_end;
continue;
}
idx += 1;
}
if let Some(mut out) = output {
if last < len {
out.push_str(&input[last..]);
}
Cow::Owned(out)
} else {
Cow::Borrowed(input)
}
}
pub fn unwrap_kept_inert_elements<'a>(
input: &'a str,
hidden_content: HiddenContent,
excluded: &[usize],
) -> Cow<'a, str> {
if hidden_content == HiddenContent::Drop {
return Cow::Borrowed(input);
}
let bytes = input.as_bytes();
let mut tag_ends = TagEndScan::new(bytes);
let Some(body_start) = body_start(input, &mut tag_ends) else {
return Cow::Borrowed(input);
};
let mut open = OpenKept::default();
let mut output: Option<String> = None;
let mut last = 0;
let mut idx = body_start;
while idx < bytes.len() {
let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) else {
break;
};
idx += offset;
let is_end_tag = bytes.get(idx + 1) == Some(&b'/');
let name_start = idx + 1 + usize::from(is_end_tag);
let is_template = matches_tag_start(bytes, name_start, b"template");
let is_noscript = matches_tag_start(bytes, name_start, b"noscript");
let is_tag = opens_a_tag(bytes, idx);
let tag_end = if is_tag { tag_ends.tag_end(idx + 1) } else { None };
if !is_template && !is_noscript {
let unit_end = if is_tag && tag_end.is_none() {
None
} else {
skip_opaque_region(bytes, idx)
.or_else(|| skip_written_text_element(bytes, idx))
.or(tag_end)
};
idx = unit_end.unwrap_or(idx + 1);
continue;
}
let Some(tag_end) = tag_end else {
break;
};
let starts_body = idx == body_start;
let kind = usize::from(is_noscript);
let step = if is_end_tag {
open.end(kind)
} else {
let remove =
hidden_content == HiddenContent::All || (is_template && tag_declares_shadow_root(&input[idx..tag_end]));
open.start(kind, remove, excluded.binary_search(&idx).is_ok())
};
match step {
TagStep::Stays => {}
TagStep::Removed => {
let out = output.get_or_insert_with(|| String::with_capacity(bytes.len()));
out.push_str(&input[last..idx]);
out.push_str(if starts_body { BODY_START } else { "" });
last = tag_end;
}
TagStep::ExcludedEnds => last = tag_end,
}
idx = tag_end;
}
match output {
Some(mut out) => {
out.push_str(if open.in_excluded() { "" } else { &input[last..] });
Cow::Owned(out)
}
None => Cow::Borrowed(input),
}
}
const BODY_START: &str = "</body>";
fn tag_declares_shadow_root(tag: &str) -> bool {
extract_attribute_value(tag, "shadowrootmode")
.is_some_and(|mode| mode.eq_ignore_ascii_case("open") || mode.eq_ignore_ascii_case("closed"))
}
const fn skip_attribute_value(bytes: &[u8], mut i: usize, len: usize) -> usize {
if i >= len || bytes[i] != b'=' {
return i;
}
i += 1;
while i < len && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i < len && (bytes[i] == b'"' || bytes[i] == b'\'') {
let quote = bytes[i];
i += 1;
while i < len && bytes[i] != quote {
i += 1;
}
i += 1;
} else {
while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
i += 1;
}
}
i
}
pub fn tag_has_hidden_attribute(tag: &str) -> bool {
let bytes = tag.as_bytes();
let len = bytes.len();
let mut i = 0;
while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
i += 1;
}
while i < len {
while i < len && (bytes[i].is_ascii_whitespace() || bytes[i] == b'/') {
i += 1;
}
if i >= len || bytes[i] == b'>' {
return false;
}
let name_start = i;
while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'=' && bytes[i] != b'>' && bytes[i] != b'/' {
i += 1;
}
let name = &bytes[name_start..i];
while i < len && bytes[i].is_ascii_whitespace() {
i += 1;
}
i = skip_attribute_value(bytes, i, len);
if name.eq_ignore_ascii_case(b"hidden") {
return true;
}
}
false
}
fn strip_css_comments(declaration: &str) -> Cow<'_, str> {
if !declaration.contains("/*") {
return Cow::Borrowed(declaration);
}
let mut out = String::with_capacity(declaration.len());
let mut rest = declaration;
while let Some(start) = rest.find("/*") {
out.push_str(&rest[..start]);
let Some(end) = rest[start + 2..].find("*/") else {
rest = "";
break;
};
rest = &rest[start + 2 + end + 2..];
}
out.push_str(rest);
Cow::Owned(out)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HiddenStyleReason {
Definitive,
FontSizeZero,
}
fn scan_visibility_declarations(style_value: &str) -> (bool, bool, Option<bool>) {
let mut display_hides = false;
let mut visibility_hides = false;
let mut font_size_zero = None;
for declaration in style_value.split(';') {
let cleaned = strip_css_comments(declaration);
let Some((property, value)) = cleaned.split_once(':') else {
continue;
};
let property = property.trim();
let value = value.split('!').next().unwrap_or("").trim();
if property.eq_ignore_ascii_case("display") {
display_hides = value.eq_ignore_ascii_case("none");
} else if property.eq_ignore_ascii_case("visibility") {
visibility_hides = value.eq_ignore_ascii_case("hidden");
} else if property.eq_ignore_ascii_case("font-size") {
font_size_zero = Some(css_length_is_zero(value));
}
}
(display_hides, visibility_hides, font_size_zero)
}
fn css_length_is_zero(value: &str) -> bool {
const ZERO_UNITS: [&str; 16] = [
"px", "pt", "pc", "em", "rem", "ex", "ch", "vw", "vh", "vmin", "vmax", "cm", "mm", "in", "q", "%",
];
let digits_end = value
.find(|c: char| !c.is_ascii_digit() && c != '.')
.unwrap_or(value.len());
let (number, unit) = value.split_at(digits_end);
if number.is_empty() || number == "." || number.matches('.').count() > 1 {
return false;
}
if number.bytes().any(|b| b != b'0' && b != b'.') {
return false;
}
let unit = unit.trim();
unit.is_empty() || ZERO_UNITS.iter().any(|candidate| unit.eq_ignore_ascii_case(candidate))
}
pub fn hidden_style_reason(tag: &str) -> Option<HiddenStyleReason> {
style_value_hidden_reason(extract_attribute_value(tag, "style")?)
}
pub fn style_value_hidden_reason(style_value: &str) -> Option<HiddenStyleReason> {
let (display_hides, visibility_hides, font_size_zero) = scan_visibility_declarations(style_value);
if display_hides || visibility_hides {
return Some(HiddenStyleReason::Definitive);
}
if font_size_zero == Some(true) {
return Some(HiddenStyleReason::FontSizeZero);
}
None
}
fn tag_sets_non_zero_font_size(tag: &str) -> bool {
let Some(style_value) = extract_attribute_value(tag, "style") else {
return false;
};
scan_visibility_declarations(style_value).2 == Some(false)
}
fn region_restores_visible_content(region: &str) -> bool {
let bytes = region.as_bytes();
let len = bytes.len();
let mut idx = 0;
let mut ends = None;
while idx < len {
if let Some(end) = skip_opaque_region(bytes, idx) {
idx = end;
continue;
}
if bytes[idx] == b'<' && idx + 1 < len && bytes[idx + 1].is_ascii_alphabetic() {
if let Some(tag_end) = find_tag_end(bytes, idx + 1) {
let tag = ®ion[idx..tag_end];
if tag_has_hidden_attribute(tag) || hidden_style_reason(tag) == Some(HiddenStyleReason::Definitive) {
idx = hidden_element_remove_end(bytes, idx, tag_end, &mut ends);
continue;
}
if tag_sets_non_zero_font_size(tag) || matches_tag_start(bytes, idx + 1, b"img") {
return true;
}
idx = tag_end;
continue;
}
}
idx += 1;
}
false
}
pub fn tag_has_hidden_style(tag: &str) -> bool {
hidden_style_reason(tag).is_some()
}
fn scan_optional_attribute_value<'a>(bytes: &[u8], tag: &'a str, mut i: usize, len: usize) -> (Option<&'a str>, usize) {
if i >= len || bytes[i] != b'=' {
return (None, i);
}
i += 1;
while i < len && bytes[i].is_ascii_whitespace() {
i += 1;
}
let (val, next) = scan_attribute_value(bytes, tag, i);
(Some(val), next)
}
fn extract_attribute_value<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> {
let bytes = tag.as_bytes();
let len = bytes.len();
let mut i = 0;
while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
i += 1;
}
while i < len {
while i < len && (bytes[i].is_ascii_whitespace() || bytes[i] == b'/') {
i += 1;
}
if i >= len || bytes[i] == b'>' {
break;
}
let name_start = i;
while i < len && bytes[i] != b'=' && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' && bytes[i] != b'/' {
i += 1;
}
let name = &tag[name_start..i];
while i < len && bytes[i].is_ascii_whitespace() {
i += 1;
}
let (value, next_i) = scan_optional_attribute_value(bytes, tag, i, len);
i = next_i;
if name.eq_ignore_ascii_case(attr_name) {
return value;
}
}
None
}
fn scan_attribute_value<'a>(bytes: &[u8], tag: &'a str, start: usize) -> (&'a str, usize) {
let len = bytes.len();
if start < len && (bytes[start] == b'"' || bytes[start] == b'\'') {
let quote = bytes[start];
let val_start = start + 1;
let mut end = val_start;
while end < len && bytes[end] != quote {
end += 1;
}
let value = &tag[val_start..end];
let next = if end < len { end + 1 } else { end };
return (value, next);
}
let val_start = start;
let mut end = start;
while end < len && !bytes[end].is_ascii_whitespace() && bytes[end] != b'>' {
end += 1;
}
(&tag[val_start..end], end)
}
#[cfg(test)]
mod tag_ends_tests;