use std::borrow::Cow;
#[must_use]
pub fn is_djot_rule_like(text: &str) -> bool {
text.contains('*')
&& text
.chars()
.all(|character| matches!(character, '-' | '*') || character.is_whitespace())
}
#[inline]
const fn is_misc_escape(b: u8) -> bool {
matches!(
b,
b'\\' | b'&' | b'<' | b'`' | b'[' | b']' | b'>' | b'~' | b'#' | b'=' | b'+' | b'|' | b'-'
)
}
#[inline]
pub const fn backslash_needs_escape(bytes: &[u8], i: usize) -> bool {
if i + 1 >= bytes.len() {
return true;
}
let next = bytes[i + 1];
matches!(next, b'\n' | b'\r') || is_ascii_punct(next)
}
#[inline]
const fn is_ascii_punct(b: u8) -> bool {
matches!(
b,
b'!' | b'"'
| b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'('
| b')'
| b'*'
| b'+'
| b','
| b'-'
| b'.'
| b'/'
| b':'
| b';'
| b'<'
| b'='
| b'>'
| b'?'
| b'@'
| b'['
| b'\\'
| b']'
| b'^'
| b'_'
| b'`'
| b'{'
| b'|'
| b'}'
| b'~'
)
}
#[allow(clippy::fn_params_excessive_bools)]
pub fn escape_into(
dest: &mut String,
text: &str,
escape_misc: bool,
escape_asterisks: bool,
escape_underscores: bool,
escape_ascii: bool,
) {
if text.is_empty() {
return;
}
if escape_ascii {
escape_ascii_into(dest, text);
return;
}
let bytes = text.as_bytes();
let mut run_start = 0;
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
let needs_misc = escape_misc && is_misc_escape(b);
let needs_numbered = escape_misc && (b == b'.' || b == b')') && i > 0 && bytes[i - 1].is_ascii_digit();
let needs_star = escape_asterisks && b == b'*';
let needs_under = escape_underscores && b == b'_';
let needs_backslash = b == b'\\' && backslash_needs_escape(bytes, i);
if needs_misc || needs_numbered || needs_star || needs_under || needs_backslash {
if i > run_start {
dest.push_str(&text[run_start..i]);
}
dest.push('\\');
dest.push(b as char);
i += 1;
run_start = i;
} else {
i += 1;
}
}
if i > run_start {
dest.push_str(&text[run_start..]);
}
}
fn escape_ascii_into(dest: &mut String, text: &str) {
let bytes = text.as_bytes();
let mut run_start = 0;
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if is_ascii_punct(b) {
if i > run_start {
dest.push_str(&text[run_start..i]);
}
dest.push('\\');
dest.push(b as char);
i += 1;
run_start = i;
} else {
i += 1;
}
}
if i > run_start {
dest.push_str(&text[run_start..]);
}
}
#[allow(clippy::fn_params_excessive_bools)]
pub fn escape(
text: &str,
escape_misc: bool,
escape_asterisks: bool,
escape_underscores: bool,
escape_ascii: bool,
) -> Cow<'_, str> {
if text.is_empty() {
return Cow::Borrowed("");
}
if !escape_misc && !escape_asterisks && !escape_underscores && !escape_ascii && !text.contains('\\') {
return Cow::Borrowed(text);
}
let bytes = text.as_bytes();
let needs_any = bytes.iter().enumerate().any(|(i, &b)| {
if escape_ascii {
return is_ascii_punct(b);
}
(escape_misc && (is_misc_escape(b) || b == b'.' || b == b')'))
|| (escape_asterisks && b == b'*')
|| (escape_underscores && b == b'_')
|| (b == b'\\' && backslash_needs_escape(bytes, i))
});
if !needs_any {
return Cow::Borrowed(text);
}
let mut dest = String::with_capacity(text.len() + 8);
escape_into(
&mut dest,
text,
escape_misc,
escape_asterisks,
escape_underscores,
escape_ascii,
);
Cow::Owned(dest)
}
#[must_use]
pub fn chomp(text: &str) -> (&str, &str, &str) {
if text.is_empty() {
return ("", "", "");
}
let prefix = if text.starts_with(|c: char| c.is_whitespace()) {
" "
} else {
""
};
let suffix = if text.ends_with("\n\n") || text.ends_with("\r\n\r\n") {
"\n\n"
} else if text.ends_with([' ', '\t']) {
" "
} else {
""
};
let trimmed = if suffix == "\n\n" {
text.trim_end_matches("\n\n").trim_end_matches("\r\n\r\n").trim()
} else {
text.trim()
};
(prefix, suffix, trimmed)
}
#[must_use]
pub fn normalize_whitespace(text: &str) -> String {
let mut result = String::with_capacity(text.len());
let mut prev_was_space = false;
for ch in text.chars() {
let is_space = ch == ' ' || ch == '\t' || is_unicode_space(ch);
if is_space {
if !prev_was_space {
result.push(' ');
prev_was_space = true;
}
} else {
result.push(ch);
prev_was_space = false;
}
}
result
}
#[must_use]
pub fn normalize_whitespace_cow(text: &str) -> Cow<'_, str> {
let bytes = text.as_bytes();
let mut prev_was_space = false;
for &b in bytes {
if b >= 0x80 {
return normalize_whitespace_cow_slow(text);
}
let is_space = b == b' ' || b == b'\t';
if is_space {
if prev_was_space || b != b' ' {
return Cow::Owned(normalize_whitespace(text));
}
prev_was_space = true;
} else {
prev_was_space = false;
}
}
Cow::Borrowed(text)
}
#[cold]
fn normalize_whitespace_cow_slow(text: &str) -> Cow<'_, str> {
let mut prev_was_space = false;
for ch in text.chars() {
let is_space = ch == ' ' || ch == '\t' || is_unicode_space(ch);
if is_space {
if prev_was_space || ch != ' ' {
return Cow::Owned(normalize_whitespace(text));
}
prev_was_space = true;
} else {
prev_was_space = false;
}
}
Cow::Borrowed(text)
}
#[must_use]
pub fn normalize_block_whitespace_cow(text: &str) -> Cow<'_, str> {
let bytes = text.as_bytes();
let mut prev_was_space = false;
let mut at_line_start = false;
for &b in bytes {
if b >= 0x80 {
return Cow::Owned(normalize_block_whitespace(text));
}
if b == b'\n' {
prev_was_space = false;
at_line_start = true;
continue;
}
let is_space = b == b' ' || b == b'\t';
if is_space {
if at_line_start || prev_was_space {
return Cow::Owned(normalize_block_whitespace(text));
}
prev_was_space = true;
} else {
prev_was_space = false;
at_line_start = false;
}
}
Cow::Borrowed(text)
}
#[cold]
fn normalize_block_whitespace(text: &str) -> String {
let mut result = String::with_capacity(text.len());
let mut prev_was_space = false;
let mut at_line_start = false;
for ch in text.chars() {
if ch == '\n' {
result.push(ch);
prev_was_space = false;
at_line_start = true;
continue;
}
let is_space = ch == ' ' || ch == '\t' || is_unicode_space(ch);
if is_space {
if at_line_start {
continue;
}
if !prev_was_space {
result.push(' ');
prev_was_space = true;
}
} else {
result.push(ch);
prev_was_space = false;
at_line_start = false;
}
}
result
}
#[must_use]
pub fn normalize_cell_whitespace_cow(text: &str) -> Cow<'_, str> {
if !text.contains('\n') && !text.contains('\r') {
return normalize_whitespace_cow(text);
}
let folded = text.replace(['\n', '\r'], " ");
Cow::Owned(normalize_whitespace(&folded))
}
#[must_use]
pub fn fold_cell_line_breaks_verbatim_cow(text: &str) -> Cow<'_, str> {
if !text.contains('\n') && !text.contains('\r') {
return Cow::Borrowed(text);
}
let mut folded = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'\r' => {
if chars.peek() == Some(&'\n') {
chars.next();
}
folded.push(' ');
}
'\n' => folded.push(' '),
other => folded.push(other),
}
}
Cow::Owned(folded)
}
pub fn parse_character_reference_number(digits: &str, radix: u32) -> Result<u64, ()> {
match u64::from_str_radix(digits, radix) {
Ok(number) => Ok(number),
Err(err) if *err.kind() == std::num::IntErrorKind::PosOverflow => Ok(u64::MAX),
Err(_) => Err(()),
}
}
#[must_use]
pub fn numeric_character_reference_override(value: u64) -> Option<char> {
if value == 0 || value > 0x0010_FFFF || (0xD800..=0xDFFF).contains(&value) {
return Some('\u{FFFD}');
}
let replacement = match value {
0x80 => '\u{20AC}',
0x82 => '\u{201A}',
0x83 => '\u{0192}',
0x84 => '\u{201E}',
0x85 => '\u{2026}',
0x86 => '\u{2020}',
0x87 => '\u{2021}',
0x88 => '\u{02C6}',
0x89 => '\u{2030}',
0x8A => '\u{0160}',
0x8B => '\u{2039}',
0x8C => '\u{0152}',
0x8E => '\u{017D}',
0x91 => '\u{2018}',
0x92 => '\u{2019}',
0x93 => '\u{201C}',
0x94 => '\u{201D}',
0x95 => '\u{2022}',
0x96 => '\u{2013}',
0x97 => '\u{2014}',
0x98 => '\u{02DC}',
0x99 => '\u{2122}',
0x9A => '\u{0161}',
0x9B => '\u{203A}',
0x9C => '\u{0153}',
0x9E => '\u{017E}',
0x9F => '\u{0178}',
_ => return None,
};
Some(replacement)
}
fn scan_numeric_character_reference(bytes: &[u8], amp: usize) -> Option<(usize, u64)> {
if bytes.get(amp + 1) != Some(&b'#') {
return None;
}
let mut digits_start = amp + 2;
let is_hex = matches!(bytes.get(digits_start), Some(b'x' | b'X'));
if is_hex {
digits_start += 1;
}
let is_valid_digit: fn(&u8) -> bool = if is_hex {
u8::is_ascii_hexdigit
} else {
u8::is_ascii_digit
};
let digits_end = digits_start + bytes[digits_start..].iter().take_while(|b| is_valid_digit(b)).count();
let digits_str = std::str::from_utf8(&bytes[digits_start..digits_end]).unwrap_or_default();
let radix = if is_hex { 16 } else { 10 };
let value = parse_character_reference_number(digits_str, radix).ok()?;
let end = if bytes.get(digits_end) == Some(&b';') {
digits_end + 1
} else {
digits_end
};
Some((end, value))
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ReferenceContext {
Text,
Attribute,
}
#[must_use]
pub fn decode_character_reference(
text: &str,
amp: usize,
context: ReferenceContext,
) -> Option<(usize, char, Option<char>)> {
let bytes = text.as_bytes();
if bytes.get(amp + 1) == Some(&b'#') {
let (end, value) = scan_numeric_character_reference(bytes, amp)?;
if let Some(replacement) = numeric_character_reference_override(value) {
return Some((end, replacement, None));
}
let ch = char::from_u32(u32::try_from(value).ok()?)?;
if matches!(ch, '\0'..='\u{1F}') && !matches!(ch, '\t' | '\n' | '\u{000C}' | '\r') {
return None;
}
return Some((end, ch, None));
}
let lookup = |name: &str| match html5ever::data::NAMED_ENTITIES.get(name) {
Some(&(first, second)) if first != 0 => {
Some((char::from_u32(first)?, char::from_u32(second).filter(|&c| c != '\0')))
}
_ => None,
};
let name_start = amp + 1;
let name_len = bytes[name_start..]
.iter()
.take_while(|b| b.is_ascii_alphanumeric())
.count();
if name_len == 0 {
return None;
}
let name_end = name_start + name_len;
if bytes.get(name_end) == Some(&b';') {
if let Some((first, second)) = lookup(&text[name_start..=name_end]) {
return Some((name_end + 1, first, second));
}
}
for len in (2..=name_len.min(6)).rev() {
let end = name_start + len;
if let Some((first, second)) = lookup(&text[name_start..end]) {
let next = bytes.get(end).copied();
if context == ReferenceContext::Attribute && next.is_some_and(|b| b == b'=' || b.is_ascii_alphanumeric()) {
return None;
}
return Some((end, first, second));
}
}
None
}
fn decode_character_references(text: &str, context: ReferenceContext) -> Cow<'_, str> {
let bytes = text.as_bytes();
let mut out = String::new();
let mut copied = 0;
let mut i = 0;
while let Some(rel) = memchr::memchr(b'&', &bytes[i..]) {
let amp = i + rel;
match decode_character_reference(text, amp, context) {
Some((end, first, second)) => {
if out.is_empty() {
out.reserve(text.len());
}
out.push_str(&text[copied..amp]);
out.push(first);
if let Some(second) = second {
out.push(second);
}
copied = end;
i = end;
}
None => i = amp + 1,
}
}
if copied == 0 {
return Cow::Borrowed(text);
}
out.push_str(&text[copied..]);
Cow::Owned(out)
}
#[must_use]
pub fn decode_html_entities_cow(text: &str) -> Cow<'_, str> {
decode_character_references(text, ReferenceContext::Text)
}
#[must_use]
pub fn decode_attribute_value_cow(value: &str) -> Cow<'_, str> {
decode_character_references(value, ReferenceContext::Attribute)
}
const fn is_unicode_space(ch: char) -> bool {
matches!(
ch,
'\u{00A0}'
| '\u{1680}'
| '\u{2000}'
| '\u{2001}'
| '\u{2002}'
| '\u{2003}'
| '\u{2004}'
| '\u{2005}'
| '\u{2006}'
| '\u{2007}'
| '\u{2008}'
| '\u{2009}'
| '\u{200A}'
| '\u{202F}'
| '\u{205F}'
| '\u{3000}'
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_escape_misc() {
assert_eq!(escape("foo & bar", true, false, false, false), r"foo \& bar");
assert_eq!(escape("foo [bar]", true, false, false, false), r"foo \[bar\]");
assert_eq!(escape("1. Item", true, false, false, false), r"1\. Item");
assert_eq!(escape("1) Item", true, false, false, false), r"1\) Item");
}
#[test]
fn test_escape_asterisks() {
assert_eq!(escape("foo * bar", false, true, false, false), r"foo \* bar");
assert_eq!(escape("**bold**", false, true, false, false), r"\*\*bold\*\*");
}
#[test]
fn test_escape_underscores() {
assert_eq!(escape("foo_bar", false, false, true, false), r"foo\_bar");
assert_eq!(escape("__bold__", false, false, true, false), r"\_\_bold\_\_");
}
#[test]
fn test_escape_ascii() {
assert_eq!(escape(r##"!"#$%&"##, false, false, false, true), r#"\!\"\#\$\%\&"#);
assert_eq!(escape("*+,-./", false, false, false, true), r"\*\+\,\-\.\/");
assert_eq!(escape("<=>?@", false, false, false, true), r"\<\=\>\?\@");
assert_eq!(escape(r"[\]^_`", false, false, false, true), r"\[\\\]\^\_\`");
assert_eq!(escape("{|}~", false, false, false, true), r"\{\|\}\~");
}
#[test]
fn should_escape_backslash_before_ascii_punctuation_even_with_all_flags_false() {
assert_eq!(escape(r"a\*b", false, false, false, false), r"a\\*b");
assert_eq!(escape(r"3\.14", false, false, false, false), r"3\\.14");
assert_eq!(escape(r"a\[b\]c", false, false, false, false), r"a\\[b\\]c");
}
#[test]
fn should_not_escape_backslash_before_non_punctuation() {
assert_eq!(escape(r"a\3b", false, false, false, false), r"a\3b");
assert_eq!(escape(r"C:\Users\Alice", false, false, false, false), r"C:\Users\Alice");
assert_eq!(escape("a\\ b", false, false, false, false), "a\\ b");
}
#[test]
fn should_escape_backslash_at_end_of_text_run() {
assert_eq!(escape(r"abc\", false, false, false, false), r"abc\\");
assert_eq!(escape(r"\", false, false, false, false), r"\\");
}
#[test]
fn should_escape_backslash_before_line_ending_to_avoid_hard_break_collision() {
assert_eq!(escape("abc\\\ndef", false, false, false, false), "abc\\\\\ndef");
assert_eq!(escape("abc\\\r\ndef", false, false, false, false), "abc\\\\\r\ndef");
}
#[test]
fn should_escape_consecutive_backslashes_pairwise() {
assert_eq!(escape(r"a\\b", false, false, false, false), r"a\\\b");
}
#[test]
fn should_escape_backslash_independently_of_escape_misc() {
assert_eq!(escape(r"a\*b", true, false, false, false), r"a\\*b");
assert_eq!(escape(r"a\3b", true, false, false, false), r"a\\3b");
}
#[test]
fn should_borrow_unchanged_when_no_backslash_needs_escaping() {
assert!(matches!(
escape(r"a\3b", false, false, false, false),
std::borrow::Cow::Borrowed(_)
));
assert!(matches!(
escape("plain", false, false, false, false),
std::borrow::Cow::Borrowed(_)
));
}
#[test]
fn test_chomp() {
assert_eq!(chomp(" text "), (" ", " ", "text"));
assert_eq!(chomp("text"), ("", "", "text"));
assert_eq!(chomp(" text"), (" ", "", "text"));
assert_eq!(chomp("text "), ("", " ", "text"));
assert_eq!(chomp(""), ("", "", ""));
}
#[test]
fn legacy_names_fit_the_six_byte_scan() {
let longest = html5ever::data::NAMED_ENTITIES
.entries()
.filter(|(name, value)| !name.ends_with(';') && value.0 != 0)
.map(|(name, _)| name.len())
.max();
assert_eq!(longest, Some(6));
}
#[test]
fn character_references_decode_per_context() {
let cases = [
("© 2024", "\u{a9} 2024", "\u{a9} 2024"),
("a©=2", "a\u{a9}=2", "a©=2"),
("©right", "\u{a9}right", "©right"),
("¬it;", "\u{ac}it;", "¬it;"),
("∉", "\u{2209}", "\u{2209}"),
("&copy", "©", "©"),
("&hellip x", "&hellip x", "&hellip x"),
("≂̸", "\u{2242}\u{338}", "\u{2242}\u{338}"),
("–A	", "\u{2013}A\t", "\u{2013}A\t"),
("& &; &#; &#x; &#xg;", "& &; &#; &#x; &#xg;", "& &; &#; &#x; &#xg;"),
("'s'=A", "'s'=A", "'s'=A"),
("a;b", "\u{c}a;b", "\u{c}a;b"),
("�x", "\u{fffd}x", "\u{fffd}x"),
];
for (input, text, attribute) in cases {
assert_eq!(decode_html_entities_cow(input), text, "text: {input:?}");
assert_eq!(decode_attribute_value_cow(input), attribute, "attribute: {input:?}");
}
assert!(matches!(decode_html_entities_cow("a & b"), Cow::Borrowed(_)));
}
}