use std::sync::OnceLock;
use regex::Regex;
use crate::entities;
pub const ESCAPABLE_ASCII: &str = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
pub const ENTITY_PATTERN: &str =
r"&(?:#[xX][a-fA-F0-9]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{1,31});";
fn re_entity_or_escaped_char() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(&format!(
r"\\[{}]|{}",
regex::escape(ESCAPABLE_ASCII),
ENTITY_PATTERN
))
.expect("the unescape pattern is a literal and compiles")
})
}
fn re_entity_whole() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(&format!("^(?:{ENTITY_PATTERN})$"))
.expect("the entity pattern is a literal and compiles")
})
}
fn re_whitespace_run() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"[ \t\r\n]+").expect("a literal pattern compiles"))
}
fn re_unicode_punctuation() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[\p{P}\p{S}]$").expect("a literal pattern compiles"))
}
pub fn is_escapable(b: u8) -> bool {
ESCAPABLE_ASCII.as_bytes().contains(&b)
}
pub fn is_unicode_whitespace(c: char) -> bool {
matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' ')
|| matches!(
c,
'\u{00A0}'
| '\u{1680}'
| '\u{2028}'
| '\u{2029}'
| '\u{202F}'
| '\u{205F}'
| '\u{3000}'
)
|| ('\u{2000}'..='\u{200A}').contains(&c)
}
pub fn is_unicode_punctuation(c: char) -> bool {
if c.is_ascii() {
return is_escapable(c as u8);
}
let mut buf = [0u8; 4];
re_unicode_punctuation().is_match(c.encode_utf8(&mut buf))
}
pub fn decode_entity(text: &str) -> String {
if !re_entity_whole().is_match(text) {
return text.to_string();
}
let body = &text[1..text.len() - 1];
if let Some(numeric) = body.strip_prefix('#') {
let (digits, radix) = match numeric.strip_prefix(['x', 'X']) {
Some(hex) => (hex, 16),
None => (numeric, 10),
};
let cp = u32::from_str_radix(digits, radix).ok();
return match cp {
Some(cp) if cp != 0 && cp <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&cp) => {
char::from_u32(cp)
.map(|c| c.to_string())
.unwrap_or_else(|| "\u{FFFD}".to_string())
}
_ => "\u{FFFD}".to_string(),
};
}
match entities::lookup(body) {
Some(replacement) => replacement.to_string(),
None => text.to_string(),
}
}
pub fn unescape_string(s: &str) -> String {
if !s.contains(['\\', '&']) {
return s.to_string();
}
re_entity_or_escaped_char()
.replace_all(s, |captures: ®ex::Captures<'_>| {
let m = &captures[0];
if let Some(escaped) = m.strip_prefix('\\') {
escaped.to_string()
} else {
decode_entity(m)
}
})
.into_owned()
}
pub fn is_js_space(c: char) -> bool {
c == '\u{b}' || c == '\u{FEFF}' || is_unicode_whitespace(c)
}
pub fn js_trim(s: &str) -> &str {
s.trim_matches(is_js_space)
}
pub fn js_space_index(s: &str) -> Option<(usize, usize)> {
s.char_indices()
.find(|(_, c)| is_js_space(*c))
.map(|(index, c)| (index, c.len_utf8()))
}
pub fn normalize_reference(raw_label: &str) -> String {
let trimmed = js_trim(raw_label);
let collapsed = re_whitespace_run().replace_all(trimmed, " ");
if collapsed.is_ascii() {
return collapsed.to_ascii_uppercase();
}
collapsed.to_lowercase().to_uppercase()
}
pub fn escape_xml(s: &str) -> String {
if !s.contains(['&', '<', '>', '"']) {
return s.to_string();
}
let mut out = String::with_capacity(s.len() + 8);
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
c => out.push(c),
}
}
out
}
const URL_SAFE: &str = ";/?:@&=+$,-_.!~*'()#";
fn is_url_safe(b: u8) -> bool {
b.is_ascii_alphanumeric() || URL_SAFE.as_bytes().contains(&b)
}
const UPPER_HEX: &[u8; 16] = b"0123456789ABCDEF";
fn push_percent(out: &mut String, b: u8) {
out.push('%');
out.push(UPPER_HEX[(b >> 4) as usize] as char);
out.push(UPPER_HEX[(b & 0x0F) as usize] as char);
}
pub fn normalize_uri(uri: &str) -> String {
let bytes = uri.as_bytes();
let mut out = String::with_capacity(uri.len());
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
if c == b'%'
&& i + 2 < bytes.len()
&& bytes[i + 1].is_ascii_hexdigit()
&& bytes[i + 2].is_ascii_hexdigit()
{
out.push_str(&uri[i..i + 3]);
i += 3;
continue;
}
if c.is_ascii() {
if is_url_safe(c) {
out.push(c as char);
} else {
push_percent(&mut out, c);
}
i += 1;
continue;
}
push_percent(&mut out, c);
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn entities_decode_per_section_6_2() {
assert_eq!(decode_entity("&"), "&");
assert_eq!(decode_entity("A"), "A");
assert_eq!(decode_entity("A"), "A");
assert_eq!(decode_entity("�"), "\u{FFFD}");
assert_eq!(decode_entity("�"), "\u{FFFD}");
assert_eq!(decode_entity("�"), "\u{FFFD}");
assert_eq!(decode_entity("&nosuch;"), "&nosuch;");
assert_eq!(decode_entity("&a;"), "&a;");
assert_eq!(decode_entity("&"), "&");
assert_eq!(decode_entity("≫⃒"), "\u{226B}\u{20D2}");
}
#[test]
fn unescape_resolves_both_forms_together() {
assert_eq!(unescape_string(r"\*a\* & b"), "*a* & b");
assert_eq!(unescape_string("plain"), "plain");
assert_eq!(unescape_string(r"\a"), r"\a");
}
#[test]
fn label_normalisation_uses_full_case_mapping() {
assert_eq!(normalize_reference(" Foo Bar "), "FOO BAR");
assert_eq!(normalize_reference("ẞ"), normalize_reference("SS"));
assert_eq!(normalize_reference("Σ"), normalize_reference("ς"));
}
#[test]
fn punctuation_is_p_union_s() {
for c in [
'$', '+', '<', '=', '>', '^', '`', '|', '~', '£', '€', '«', '。',
] {
assert!(is_unicode_punctuation(c), "{c:?}");
}
for c in ['a', '1', ' ', 'é', '\u{200B}'] {
assert!(!is_unicode_punctuation(c), "{c:?}");
}
}
#[test]
fn uri_normalisation_matches_the_reference_renderer() {
assert_eq!(normalize_uri("/ä"), "/%C3%A4");
assert_eq!(normalize_uri("/a%20b"), "/a%20b");
assert_eq!(normalize_uri("/a b"), "/a%20b");
assert_eq!(
normalize_uri("http://x.y/?q=1&r=(2)"),
"http://x.y/?q=1&r=(2)"
);
}
#[test]
fn xml_escaping() {
assert_eq!(escape_xml("a<b>&\"c"), "a<b>&"c");
}
}