tabnas_markdown/
common.rs1use std::sync::OnceLock;
23
24use regex::Regex;
25
26use crate::entities;
27
28pub const ESCAPABLE_ASCII: &str = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
31
32pub const ENTITY_PATTERN: &str =
36 r"&(?:#[xX][a-fA-F0-9]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{1,31});";
37
38fn re_entity_or_escaped_char() -> &'static Regex {
39 static RE: OnceLock<Regex> = OnceLock::new();
40 RE.get_or_init(|| {
41 Regex::new(&format!(
42 r"\\[{}]|{}",
43 regex::escape(ESCAPABLE_ASCII),
44 ENTITY_PATTERN
45 ))
46 .expect("the unescape pattern is a literal and compiles")
47 })
48}
49
50fn re_entity_whole() -> &'static Regex {
51 static RE: OnceLock<Regex> = OnceLock::new();
52 RE.get_or_init(|| {
53 Regex::new(&format!("^(?:{ENTITY_PATTERN})$"))
54 .expect("the entity pattern is a literal and compiles")
55 })
56}
57
58fn re_whitespace_run() -> &'static Regex {
59 static RE: OnceLock<Regex> = OnceLock::new();
60 RE.get_or_init(|| Regex::new(r"[ \t\r\n]+").expect("a literal pattern compiles"))
61}
62
63fn re_unicode_punctuation() -> &'static Regex {
70 static RE: OnceLock<Regex> = OnceLock::new();
71 RE.get_or_init(|| Regex::new(r"^[\p{P}\p{S}]$").expect("a literal pattern compiles"))
72}
73
74pub fn is_escapable(b: u8) -> bool {
77 ESCAPABLE_ASCII.as_bytes().contains(&b)
78}
79
80pub fn is_unicode_whitespace(c: char) -> bool {
84 matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' ')
85 || matches!(
86 c,
87 '\u{00A0}'
88 | '\u{1680}'
89 | '\u{2028}'
90 | '\u{2029}'
91 | '\u{202F}'
92 | '\u{205F}'
93 | '\u{3000}'
94 )
95 || ('\u{2000}'..='\u{200A}').contains(&c)
96}
97
98pub fn is_unicode_punctuation(c: char) -> bool {
101 if c.is_ascii() {
102 return is_escapable(c as u8);
105 }
106 let mut buf = [0u8; 4];
107 re_unicode_punctuation().is_match(c.encode_utf8(&mut buf))
108}
109
110pub fn decode_entity(text: &str) -> String {
115 if !re_entity_whole().is_match(text) {
116 return text.to_string();
117 }
118
119 let body = &text[1..text.len() - 1];
120
121 if let Some(numeric) = body.strip_prefix('#') {
122 let (digits, radix) = match numeric.strip_prefix(['x', 'X']) {
123 Some(hex) => (hex, 16),
124 None => (numeric, 10),
125 };
126 let cp = u32::from_str_radix(digits, radix).ok();
127 return match cp {
128 Some(cp) if cp != 0 && cp <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&cp) => {
129 char::from_u32(cp)
130 .map(|c| c.to_string())
131 .unwrap_or_else(|| "\u{FFFD}".to_string())
132 }
133 _ => "\u{FFFD}".to_string(),
134 };
135 }
136
137 match entities::lookup(body) {
138 Some(replacement) => replacement.to_string(),
139 None => text.to_string(),
140 }
141}
142
143pub fn unescape_string(s: &str) -> String {
146 if !s.contains(['\\', '&']) {
147 return s.to_string();
148 }
149 re_entity_or_escaped_char()
150 .replace_all(s, |captures: ®ex::Captures<'_>| {
151 let m = &captures[0];
152 if let Some(escaped) = m.strip_prefix('\\') {
153 escaped.to_string()
154 } else {
155 decode_entity(m)
156 }
157 })
158 .into_owned()
159}
160
161pub fn is_js_space(c: char) -> bool {
176 c == '\u{b}' || c == '\u{FEFF}' || is_unicode_whitespace(c)
177}
178
179pub fn js_trim(s: &str) -> &str {
181 s.trim_matches(is_js_space)
182}
183
184pub fn js_space_index(s: &str) -> Option<(usize, usize)> {
191 s.char_indices()
192 .find(|(_, c)| is_js_space(*c))
193 .map(|(index, c)| (index, c.len_utf8()))
194}
195
196pub fn normalize_reference(raw_label: &str) -> String {
204 let trimmed = js_trim(raw_label);
205 let collapsed = re_whitespace_run().replace_all(trimmed, " ");
206 if collapsed.is_ascii() {
207 return collapsed.to_ascii_uppercase();
209 }
210 collapsed.to_lowercase().to_uppercase()
211}
212
213pub fn escape_xml(s: &str) -> String {
216 if !s.contains(['&', '<', '>', '"']) {
217 return s.to_string();
218 }
219 let mut out = String::with_capacity(s.len() + 8);
220 for c in s.chars() {
221 match c {
222 '&' => out.push_str("&"),
223 '<' => out.push_str("<"),
224 '>' => out.push_str(">"),
225 '"' => out.push_str("""),
226 c => out.push(c),
227 }
228 }
229 out
230}
231
232const URL_SAFE: &str = ";/?:@&=+$,-_.!~*'()#";
235
236fn is_url_safe(b: u8) -> bool {
237 b.is_ascii_alphanumeric() || URL_SAFE.as_bytes().contains(&b)
238}
239
240const UPPER_HEX: &[u8; 16] = b"0123456789ABCDEF";
241
242fn push_percent(out: &mut String, b: u8) {
243 out.push('%');
244 out.push(UPPER_HEX[(b >> 4) as usize] as char);
245 out.push(UPPER_HEX[(b & 0x0F) as usize] as char);
246}
247
248pub fn normalize_uri(uri: &str) -> String {
253 let bytes = uri.as_bytes();
254 let mut out = String::with_capacity(uri.len());
255 let mut i = 0;
256 while i < bytes.len() {
257 let c = bytes[i];
258 if c == b'%'
259 && i + 2 < bytes.len()
260 && bytes[i + 1].is_ascii_hexdigit()
261 && bytes[i + 2].is_ascii_hexdigit()
262 {
263 out.push_str(&uri[i..i + 3]);
264 i += 3;
265 continue;
266 }
267 if c.is_ascii() {
268 if is_url_safe(c) {
269 out.push(c as char);
270 } else {
271 push_percent(&mut out, c);
272 }
273 i += 1;
274 continue;
275 }
276 push_percent(&mut out, c);
278 i += 1;
279 }
280 out
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn entities_decode_per_section_6_2() {
289 assert_eq!(decode_entity("&"), "&");
290 assert_eq!(decode_entity("A"), "A");
291 assert_eq!(decode_entity("A"), "A");
292 assert_eq!(decode_entity("�"), "\u{FFFD}");
293 assert_eq!(decode_entity("�"), "\u{FFFD}");
294 assert_eq!(decode_entity("�"), "\u{FFFD}");
295 assert_eq!(decode_entity("&nosuch;"), "&nosuch;");
296 assert_eq!(decode_entity("&a;"), "&a;");
297 assert_eq!(decode_entity("&"), "&");
298 assert_eq!(decode_entity("≫⃒"), "\u{226B}\u{20D2}");
299 }
300
301 #[test]
302 fn unescape_resolves_both_forms_together() {
303 assert_eq!(unescape_string(r"\*a\* & b"), "*a* & b");
304 assert_eq!(unescape_string("plain"), "plain");
305 assert_eq!(unescape_string(r"\a"), r"\a");
306 }
307
308 #[test]
309 fn label_normalisation_uses_full_case_mapping() {
310 assert_eq!(normalize_reference(" Foo Bar "), "FOO BAR");
311 assert_eq!(normalize_reference("ẞ"), normalize_reference("SS"));
312 assert_eq!(normalize_reference("Σ"), normalize_reference("ς"));
313 }
314
315 #[test]
316 fn punctuation_is_p_union_s() {
317 for c in [
318 '$', '+', '<', '=', '>', '^', '`', '|', '~', '£', '€', '«', '。',
319 ] {
320 assert!(is_unicode_punctuation(c), "{c:?}");
321 }
322 for c in ['a', '1', ' ', 'é', '\u{200B}'] {
323 assert!(!is_unicode_punctuation(c), "{c:?}");
324 }
325 }
326
327 #[test]
328 fn uri_normalisation_matches_the_reference_renderer() {
329 assert_eq!(normalize_uri("/ä"), "/%C3%A4");
330 assert_eq!(normalize_uri("/a%20b"), "/a%20b");
331 assert_eq!(normalize_uri("/a b"), "/a%20b");
332 assert_eq!(
333 normalize_uri("http://x.y/?q=1&r=(2)"),
334 "http://x.y/?q=1&r=(2)"
335 );
336 }
337
338 #[test]
339 fn xml_escaping() {
340 assert_eq!(escape_xml("a<b>&\"c"), "a<b>&"c");
341 }
342}