pub fn escape_text(s: &str, out: &mut String) {
for ch in s.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'\x00'..='\x08' | '\x0B' | '\x0C' | '\x0E'..='\x1F' => {
use std::fmt::Write as _;
let _ = write!(out, "&#x{:X};", ch as u32);
}
c => out.push(c),
}
}
}
pub fn escape_attr(s: &str, out: &mut String) {
for ch in s.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
'\x00'..='\x08' | '\x0B' | '\x0C' | '\x0E'..='\x1F' => {
use std::fmt::Write as _;
let _ = write!(out, "&#x{:X};", ch as u32);
}
c => out.push(c),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_escapes_amp_lt_gt() {
let mut s = String::new();
escape_text("a & b < c > d", &mut s);
assert_eq!(s, "a & b < c > d");
}
#[test]
fn text_keeps_quotes() {
let mut s = String::new();
escape_text("\"hello\" 'world'", &mut s);
assert_eq!(s, "\"hello\" 'world'");
}
#[test]
fn attr_escapes_amp_lt_quot_apos() {
let mut s = String::new();
escape_attr("a & b < c \" d ' e", &mut s);
assert_eq!(s, "a & b < c " d ' e");
}
#[test]
fn attr_escapes_control_chars() {
let mut s = String::new();
escape_attr("a\x01b", &mut s);
assert_eq!(s, "ab");
let mut s = String::new();
escape_attr("\x00", &mut s);
assert_eq!(s, "�");
}
#[test]
fn attr_keeps_normal_chars() {
let mut s = String::new();
escape_attr("hello world 123 _-+=", &mut s);
assert_eq!(s, "hello world 123 _-+=");
}
#[test]
fn attr_keeps_tab_lf_cr() {
let mut s = String::new();
escape_attr("a\tb\nc\rd", &mut s);
assert_eq!(s, "a\tb\nc\rd");
}
#[test]
fn text_handles_unicode() {
let mut s = String::new();
escape_text("héllo & wörld", &mut s);
assert_eq!(s, "héllo & wörld");
}
#[test]
fn text_escapes_control_chars() {
let mut s = String::new();
escape_text("a\x01b", &mut s);
assert_eq!(s, "ab");
let mut s = String::new();
escape_text("\x00", &mut s);
assert_eq!(s, "�");
}
#[test]
fn text_keeps_tab_lf_cr() {
let mut s = String::new();
escape_text("a\tb\nc\rd", &mut s);
assert_eq!(s, "a\tb\nc\rd");
}
#[test]
fn attr_handles_unicode() {
let mut s = String::new();
escape_attr("\"héllo\"", &mut s);
assert_eq!(s, ""héllo"");
}
}