1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::get_html_data;
30use ctb_utilities::csv_tools::{self, CsvTable};
31use std::collections::HashMap;
32use std::sync::{Arc, Mutex, OnceLock};
33
34#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
36pub enum EntitySet {
37 Html32,
39 Netscape1999,
41 Xml,
43 Html4,
45 Html5,
47 MathMl,
49}
50
51impl EntitySet {
52 #[must_use]
54 pub const fn filename(self) -> &'static str {
55 match self {
56 Self::Html32 => "entities-html32.csv",
57 Self::Netscape1999 => "entities-netscape-1999.csv",
58 Self::Xml => "entities-xml.csv",
59 Self::Html4 => "entities-html4.0.csv",
60 Self::Html5 => "entities-html5.csv",
61 Self::MathMl => "entities-mathml.csv",
62 }
63 }
64
65 #[must_use]
67 pub const fn cache_key(self) -> &'static str {
68 match self {
69 Self::Html32 => "ctb_formats_html::data/entities-html32.csv",
70 Self::Netscape1999 => {
71 "ctb_formats_html::data/entities-netscape-1999.csv"
72 }
73 Self::Xml => "ctb_formats_html::data/entities-xml.csv",
74 Self::Html4 => "ctb_formats_html::data/entities-html4.0.csv",
75 Self::Html5 => "ctb_formats_html::data/entities-html5.csv",
76 Self::MathMl => "ctb_formats_html::data/entities-mathml.csv",
77 }
78 }
79}
80
81#[derive(Clone, Debug, Default)]
83pub struct EntityTable {
84 char_to_entity: HashMap<String, String>,
85 entity_to_text: HashMap<String, String>,
86 max_entity_len: usize,
87}
88
89fn parse_entity_table(
90 set: EntitySet,
91 records: &CsvTable,
92) -> Result<EntityTable> {
93 let mut char_to_entity = HashMap::new();
94 let mut entity_to_text = HashMap::new();
95
96 for row_idx in 0..records.row_count() {
97 let Some(row) = records.row(row_idx) else {
98 continue;
99 };
100 if row.is_empty() {
101 continue;
102 }
103
104 match set {
105 EntitySet::Html32 | EntitySet::Netscape1999 => {
106 if let (Some(col0), Some(col2)) = (row.first(), row.get(2)) {
108 let char_str = col0.clone();
109 let named_entity = col2.clone();
110 if !char_str.is_empty() && !named_entity.is_empty() {
111 char_to_entity
112 .entry(char_str.clone())
113 .or_insert_with(|| named_entity.clone());
114 entity_to_text.insert(named_entity, char_str);
115 }
116 }
117 }
118 EntitySet::Xml | EntitySet::Html4 => {
119 if let (Some(col0), Some(col1)) = (row.first(), row.get(1)) {
121 if let Ok(ch) =
122 crate::utilities::string::parse_dec_char(col0)
123 {
124 let char_str = ch.to_string();
125 let named_entity = format!("&{col1};");
126 char_to_entity
127 .entry(char_str.clone())
128 .or_insert_with(|| named_entity.clone());
129 entity_to_text.insert(named_entity, char_str);
130 }
131 }
132 }
133 EntitySet::Html5 => {
134 if let (Some(col0), Some(col1)) = (row.first(), row.get(1)) {
136 let mut text = String::new();
137 for part in col0.split_whitespace() {
138 if let Ok(ch) =
139 crate::utilities::string::parse_hex_char(part)
140 {
141 text.push(ch);
142 }
143 }
144 if !text.is_empty() {
145 let named_entity = format!("&{col1}");
146 entity_to_text
147 .insert(named_entity.clone(), text.clone());
148 if named_entity.ends_with(';') {
149 char_to_entity.entry(text).or_insert(named_entity);
150 }
151 }
152 }
153 }
154 EntitySet::MathMl => {
155 if let (Some(col0), Some(col1)) = (row.first(), row.get(1)) {
157 let mut text = String::new();
158 for part in col0.split_whitespace() {
159 let ch_opt = if col0.starts_with('x') {
160 crate::utilities::string::parse_hex_char(part).ok()
161 } else {
162 crate::utilities::string::parse_dec_char(part).ok()
163 };
164 if let Some(ch) = ch_opt {
165 text.push(ch);
166 }
167 }
168 if !text.is_empty() {
169 let named_entity = format!("&{col1};");
170 entity_to_text
171 .insert(named_entity.clone(), text.clone());
172 char_to_entity.entry(text).or_insert(named_entity);
173 }
174 }
175 }
176 }
177 }
178
179 let max_entity_len = match entity_to_text.keys().map(String::len).max() {
180 Some(len) => len,
181 None => 0,
182 };
183
184 Ok(EntityTable {
185 char_to_entity,
186 entity_to_text,
187 max_entity_len,
188 })
189}
190
191static ENTITY_TABLES: OnceLock<Mutex<HashMap<EntitySet, Arc<EntityTable>>>> =
192 OnceLock::new();
193
194fn get_entity_table(set: EntitySet) -> Result<Arc<EntityTable>> {
195 let map_mutex = ENTITY_TABLES.get_or_init(|| Mutex::new(HashMap::new()));
196 let mut map = map_mutex
197 .lock()
198 .map_err(|e| anyhow::anyhow!("Entity cache lock poisoned: {e}"))?;
199 if let Some(table) = map.get(&set) {
200 return Ok(Arc::clone(table));
201 }
202 let csv = csv_tools::get_or_load_cached(set.cache_key(), || {
203 let bytes = bail_if_none!(get_html_data(set.filename()));
204 csv_tools::parse_csv_reader(
205 &bytes,
206 csv_tools::CsvParseOptions {
207 has_header: false,
208 ..Default::default()
209 },
210 )
211 })?;
212 let table = Arc::new(parse_entity_table(set, &csv)?);
213 map.insert(set, Arc::clone(&table));
214 Ok(table)
215}
216
217pub fn escape_text(text: &str) -> String {
219 html_escape::encode_text(text).to_string()
220}
221
222pub fn escape_quoted_attr(text: &str) -> String {
224 html_escape::encode_quoted_attribute(text).to_string()
225}
226
227fn core_entity_for_char(ch: char, set: EntitySet) -> Option<&'static str> {
228 match ch {
229 '<' => Some("<"),
230 '>' => Some(">"),
231 '&' => Some("&"),
232 '"' => Some("""),
233 '\'' if matches!(set, EntitySet::Xml) => Some("'"),
234 _ => None,
235 }
236}
237
238fn core_char_for_entity(entity: &str) -> Option<char> {
239 match entity {
240 "<" => Some('<'),
241 ">" => Some('>'),
242 "&" => Some('&'),
243 """ => Some('"'),
244 "'" => Some('\''),
245 _ => None,
246 }
247}
248
249fn decode_numeric_entity(entity: &str) -> Option<char> {
250 let numeric = entity.strip_prefix("&#")?.strip_suffix(';')?;
251
252 let (radix, digits) = if let Some(hex) = numeric
253 .strip_prefix('x')
254 .or_else(|| numeric.strip_prefix('X'))
255 {
256 (16, hex)
257 } else {
258 (10, numeric)
259 };
260
261 let value = u32::from_str_radix(digits, radix).ok()?;
262 char::from_u32(value)
263}
264
265pub fn to_entities(input: String, set: EntitySet) -> Result<String> {
269 let table = get_entity_table(set)?;
270 let mut out = String::with_capacity(input.len());
271 for ch in input.chars() {
272 if let Some(entity) = core_entity_for_char(ch, set) {
273 out.push_str(entity);
274 } else if let Some(entity) = table.char_to_entity.get(&ch.to_string()) {
275 out.push_str(entity);
276 } else {
277 out.push(ch);
278 }
279 }
280 Ok(out)
281}
282
283pub fn from_entities(input: String, set: EntitySet) -> Result<String> {
287 let table = get_entity_table(set)?;
288 let mut i = 0usize;
289 let mut out = String::with_capacity(input.len());
290
291 while i < input.len() {
292 let Some(rest) = input.get(i..) else {
293 break;
294 };
295
296 if !rest.starts_with('&') {
297 let Some(ch) = rest.chars().next() else {
298 break;
299 };
300 out.push(ch);
301 i = i.saturating_add(ch.len_utf8());
302 continue;
303 }
304
305 if rest.starts_with("&#") {
307 if let Some(semi_pos) = rest.find(';') {
308 if let Some(candidate) = rest.get(..=semi_pos) {
309 if let Some(ch) = decode_numeric_entity(candidate) {
310 out.push(ch);
311 i = i.saturating_add(semi_pos).saturating_add(1);
312 continue;
313 }
314 }
315 }
316 }
317
318 let max_search = table.max_entity_len.min(rest.len());
321 let mut matched = false;
322
323 if let Some(semi_pos) = rest.get(..max_search).and_then(|s| s.find(';'))
324 {
325 if let Some(candidate) = rest.get(..=semi_pos) {
326 if let Some(ch) = core_char_for_entity(candidate) {
327 out.push(ch);
328 i = i.saturating_add(semi_pos).saturating_add(1);
329 matched = true;
330 } else if let Some(replacement) =
331 table.entity_to_text.get(candidate)
332 {
333 out.push_str(replacement);
334 i = i.saturating_add(semi_pos).saturating_add(1);
335 matched = true;
336 }
337 }
338 }
339
340 if matched {
341 continue;
342 }
343
344 let mut longest_len = 0usize;
346 let mut longest_replacement: Option<&str> = None;
347
348 for prefix_len in (2..=max_search).rev() {
349 if let Some(candidate) = rest.get(..prefix_len) {
350 if let Some(replacement) = table.entity_to_text.get(candidate) {
351 longest_len = prefix_len;
352 longest_replacement = Some(replacement.as_str());
353 break;
354 }
355 }
356 }
357
358 if let Some(replacement) = longest_replacement {
359 out.push_str(replacement);
360 i = i.saturating_add(longest_len);
361 continue;
362 }
363
364 out.push('&');
366 i = i.saturating_add('&'.len_utf8());
367 }
368
369 Ok(out)
370}
371
372pub fn to_entities_netscape_1999(input: String) -> Result<String> {
377 to_entities(input, EntitySet::Netscape1999)
378}
379
380pub fn from_entities_netscape_1999(input: String) -> Result<String> {
384 from_entities(input, EntitySet::Netscape1999)
385}
386
387pub fn to_entities_html32(input: String) -> Result<String> {
392 to_entities(input, EntitySet::Html32)
393}
394
395pub fn from_entities_html32(input: String) -> Result<String> {
399 from_entities(input, EntitySet::Html32)
400}
401
402pub fn to_entities_xml(input: String) -> Result<String> {
407 to_entities(input, EntitySet::Xml)
408}
409
410pub fn from_entities_xml(input: String) -> Result<String> {
414 from_entities(input, EntitySet::Xml)
415}
416
417pub fn to_entities_html4(input: String) -> Result<String> {
422 to_entities(input, EntitySet::Html4)
423}
424
425pub fn from_entities_html4(input: String) -> Result<String> {
429 from_entities(input, EntitySet::Html4)
430}
431
432pub fn to_entities_html5(input: String) -> Result<String> {
437 to_entities(input, EntitySet::Html5)
438}
439
440pub fn from_entities_html5(input: String) -> Result<String> {
444 from_entities(input, EntitySet::Html5)
445}
446
447pub fn to_entities_mathml(input: String) -> Result<String> {
452 to_entities(input, EntitySet::MathMl)
453}
454
455pub fn from_entities_mathml(input: String) -> Result<String> {
459 from_entities(input, EntitySet::MathMl)
460}
461
462#[cfg(test)]
463#[allow(
464 clippy::panic,
465 clippy::expect_used,
466 clippy::unwrap_used,
467 clippy::unwrap_in_result,
468 clippy::panic_in_result_fn,
469 clippy::indexing_slicing,
470 clippy::arithmetic_side_effects,
471 reason = "Standard repository test boilerplate"
472)]
473mod tests {
474 use super::*;
475
476 #[crate::ctb_test]
477 fn test_escape_html() {
478 assert_eq!(escape_text("Hello"), "Hello");
479 assert_eq!(escape_text("<script>"), "<script>");
480 assert_eq!(escape_text("A & B"), "A & B");
481 assert_eq!(escape_text("1 < 2 > 0"), "1 < 2 > 0");
482 }
483
484 #[crate::ctb_test]
485 fn test_escape_attr() {
486 assert_eq!(escape_quoted_attr("Hello"), "Hello");
487 assert_eq!(escape_quoted_attr("a\"b"), "a"b");
488 assert_eq!(escape_quoted_attr("it's"), "it's");
489 assert_eq!(escape_quoted_attr("a&b"), "a&b");
490 }
491
492 #[crate::ctb_test]
493 fn test_netscape_entities_1999_roundtrip_basic() -> Result<()> {
494 assert_eq!(
495 &*to_entities_netscape_1999("Å & B".to_string())?,
496 "˚ & B"
497 );
498
499 let input = "<&\"".to_string();
500 let encoded = to_entities_netscape_1999(input.clone())?;
501 assert_eq!(encoded, "<&"".to_string());
502 let decoded = from_entities_netscape_1999(encoded)?;
503 assert_eq!(decoded, input);
504 Ok(())
505 }
506
507 #[crate::ctb_test]
508 fn test_netscape_entities_1999_decodes_numeric() -> Result<()> {
509 let decoded =
510 from_entities_netscape_1999("<&"".to_string())?;
511 assert_eq!(decoded, "<&\"".to_string());
512 Ok(())
513 }
514
515 #[crate::ctb_test]
516 fn test_html32_roundtrip_basic() -> Result<()> {
517 assert_eq!(
518 &*to_entities_html32("Å & B".to_string())?,
519 "Å & B"
520 );
521
522 let input = "<&\"".to_string();
523 let encoded = to_entities_html32(input.clone())?;
524 assert_eq!(encoded, "<&"".to_string());
525 let decoded = from_entities_html32(encoded)?;
526 assert_eq!(decoded, input);
527 Ok(())
528 }
529
530 #[crate::ctb_test]
531 fn test_html32_decodes_numeric() -> Result<()> {
532 let decoded = from_entities_html32("<&"".to_string())?;
533 assert_eq!(decoded, "<&\"".to_string());
534 Ok(())
535 }
536
537 #[crate::ctb_test]
538 fn test_xml_entities() -> Result<()> {
539 let input = "<&\"'>".to_string();
540 let encoded = to_entities_xml(input.clone())?;
541 assert_eq!(encoded, "<&"'>");
542 let decoded = from_entities_xml(encoded)?;
543 assert_eq!(decoded, input);
544 Ok(())
545 }
546
547 #[crate::ctb_test]
548 fn test_html4_entities() -> Result<()> {
549 let input = "© 2026 & Co. ™".to_string();
550 let encoded = to_entities_html4(input.clone())?;
551 assert_eq!(encoded, "© 2026 & Co. ™");
552 let decoded = from_entities_html4(encoded)?;
553 assert_eq!(decoded, input);
554 Ok(())
555 }
556
557 #[crate::ctb_test]
558 fn test_html5_entities_multi_codepoint_and_semicolonless() -> Result<()> {
559 let decoded = from_entities_html5("⩭̸".to_string())?;
561 assert_eq!(decoded, "\u{2A6D}\u{338}");
562
563 let decoded_legacy = from_entities_html5("© 2026".to_string())?;
565 assert_eq!(decoded_legacy, "© 2026");
566
567 let not_decoded = from_entities_html5("&NewLine text".to_string())?;
569 assert_eq!(not_decoded, "&NewLine text");
570
571 let decoded_nl = from_entities_html5("
text".to_string())?;
573 assert_eq!(decoded_nl, "\ntext");
574
575 Ok(())
576 }
577
578 #[crate::ctb_test]
579 fn test_mathml_entities() -> Result<()> {
580 let decoded = from_entities_mathml("⩭̸".to_string())?;
581 assert_eq!(decoded, "\u{2A6D}\u{338}");
582
583 let decoded_amp = from_entities_mathml("&&".to_string())?;
584 assert_eq!(decoded_amp, "&&");
585 Ok(())
586 }
587}