//! Text escaping utilities for HTML and XML output. /// Escape HTML special characters for safe embedding in HTML content. /// /// Escapes: `&`, `<`, `>`, `"`, `'` pub fn html_escape(s: &str) -> String { let mut result = String::with_capacity(s.len()); html_escape_into(&mut result, s); result } /// Escape HTML characters into an existing string. /// /// This is more efficient when building output incrementally. fn html_escape_into(out: &mut String, s: &str) { for c in s.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), _ => out.push(c), } } } /// Escape characters for safe embedding in code blocks. /// /// Only escapes `&`, `<`, `>` — quotes are safe inside `
`.
pub fn code_escape(s: &str) -> String {
let mut result = String::with_capacity(s.len());
code_escape_into(&mut result, s);
result
}
/// Escape code block characters into an existing string.
pub fn code_escape_into(out: &mut String, s: &str) {
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
_ => out.push(c),
}
}
}
/// Escape XML special characters for safe embedding in XML documents.
///
/// Escapes: `&`, `<`, `>`, `"`, `'`
pub fn xml_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_html_escape() {
assert_eq!(html_escape("Hello & World"), "Hello & World");
assert_eq!(html_escape(""), "<tag>");
assert_eq!(html_escape("\"quoted\""), ""quoted"");
assert_eq!(html_escape("it's"), "it's");
}
#[test]
fn test_html_escape_into() {
let mut buf = String::new();
html_escape_into(&mut buf, "a < b");
assert_eq!(buf, "a < b");
}
#[test]
fn test_xml_escape() {
assert_eq!(xml_escape("Hello & World"), "Hello & World");
assert_eq!(xml_escape(""), "<tag>");
assert_eq!(xml_escape("\"quoted\""), ""quoted"");
assert_eq!(xml_escape("it's"), "it's");
}
}