const HTML_ENTITIES: &[(char, &str)] = &[
('&', "&"),
('\'', "'"),
('<', "<"),
('>', ">"),
('"', """),
];
#[must_use]
pub fn escape_html(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
push_escaped(ch, &mut out);
}
out
}
#[inline]
pub(crate) fn push_escaped(ch: char, out: &mut String) {
for &(c, entity) in HTML_ENTITIES {
if ch == c {
out.push_str(entity);
return;
}
}
out.push(ch);
}
#[must_use]
pub(crate) fn decode_html_entities(s: &str) -> String {
if !s.contains('&') {
return s.to_string();
}
let mut result = s.to_string();
for &(ch, entity) in HTML_ENTITIES {
let mut buf = [0u8; 4];
let replacement = ch.encode_utf8(&mut buf);
result = result.replace(entity, replacement);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escape_html_writes_every_special_character_as_its_entity() {
let cases: [(&str, &str); 2] = [
(
"<div class=\"test\">AT&T 'hello'</div>",
"<div class="test">AT&T 'hello'</div>",
),
(
"& < > " '",
"&amp; &lt; &gt; &quot; &#39;",
),
];
for (input, expected) in cases {
assert_eq!(escape_html(input), expected, "input: {input:?}");
}
}
#[test]
fn decode_html_entities_walks_the_table_in_order() {
let cases: [(&str, &str); 2] = [
(
"say "hi" & <tag> 'ok'",
"say \"hi\" & <tag> 'ok'",
),
("&#39;", "'"),
];
for (input, expected) in cases {
assert_eq!(decode_html_entities(input), expected, "input: {input:?}");
}
}
#[test]
fn round_trip_all_entities() {
for &(ch, _entity) in HTML_ENTITIES {
let encoded = {
let mut s = String::new();
push_escaped(ch, &mut s);
s
};
let decoded = decode_html_entities(&encoded);
assert_eq!(decoded, ch.to_string(), "round-trip failed for {ch:?}");
}
}
}