use std::borrow::Cow;
use super::markup::{find_tag_end, matches_tag_start};
use super::raw_text::{find_closing_tag_bytes_nested, is_self_closing_tag, skip_opaque_region};
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 find_subslice(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
if from >= haystack.len() {
return None;
}
memchr::memmem::find(&haystack[from..], needle).map(|off| from + off)
}
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_subslice(bytes, idx + 4, b"-->").map_or(len, |end| end + 3));
}
if next == b'!' && rest.starts_with(b"[CDATA[") {
return Some(find_subslice(bytes, idx + 9, b"]]>").map_or(len, |end| end + 3));
}
None
}
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
}
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() {
if let Some(tag_end) = find_tag_end(bytes, idx + 1) {
idx = tag_end;
continue;
}
}
idx += 1;
continue;
}
let end = memchr::memchr(b'>', &bytes[idx + 1..]).map_or(len, |off| idx + 1 + off + 1);
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, len: usize) -> usize {
let name_start = idx + 1;
let mut name_end = name_start;
while name_end < len && !bytes[name_end].is_ascii_whitespace() && bytes[name_end] != b'>' && bytes[name_end] != b'/'
{
name_end += 1;
}
let tag_name = &bytes[name_start..name_end];
if is_self_closing_tag(&bytes[idx..tag_end], tag_name) {
tag_end
} else {
find_closing_tag_bytes_nested(bytes, tag_end, tag_name).unwrap_or(tag_end)
}
}
fn hidden_element_removal_end(input: &str, bytes: &[u8], idx: usize, tag_end: usize, len: 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, len));
}
match hidden_style_reason(tag_slice)? {
HiddenStyleReason::Definitive => Some(hidden_element_remove_end(bytes, idx, tag_end, len)),
HiddenStyleReason::FontSizeZero => {
if matches_tag_start(bytes, idx + 1, b"img") {
return None;
}
let remove_end = hidden_element_remove_end(bytes, idx, tag_end, len);
let subtree = input.get(tag_end..remove_end).unwrap_or("");
(!region_restores_visible_content(subtree)).then_some(remove_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 last_gt = bytes.iter().rposition(|&b| b == b'>');
let mut idx = 0;
let mut last = 0;
let mut output: Option<String> = 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 && last_gt.is_some_and(|gt| gt > idx) {
if let Some(tag_end) = find_tag_end(bytes, idx + 1) {
if let Some(remove_end) = hidden_element_removal_end(input, bytes, idx, tag_end, len) {
let out = output.get_or_insert_with(|| String::with_capacity(len));
out.push_str(&input[last..idx]);
last = remove_end;
idx = remove_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)
}
}
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> {
let style_value = extract_attribute_value(tag, "style")?;
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;
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, len);
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)
}