pub fn escape_xml_attribute(value: &str) -> String {
escape_xml(value)
}
pub fn escape_xml_body_bounded(value: &str, max_bytes: usize, truncation_marker: &str) -> String {
let marker = truncation_marker.as_bytes();
let mut output = String::with_capacity(value.len().min(max_bytes));
let mut truncated = false;
for character in value.chars() {
let escaped = escape_xml_character(character);
if output.len().saturating_add(escaped.len()).saturating_add(marker.len()) > max_bytes {
truncated = true;
break;
}
output.push_str(&escaped);
}
if truncated {
output.push_str(truncation_marker);
}
output
}
pub fn escape_xml(value: &str) -> String {
let mut output = String::with_capacity(value.len());
for character in value.chars() {
output.push_str(&escape_xml_character(character));
}
output
}
pub fn escape_xml_character(character: char) -> String {
match character {
'&' => "&".to_owned(),
'<' => "<".to_owned(),
'>' => ">".to_owned(),
'"' => """.to_owned(),
'\'' => "'".to_owned(),
character if character.is_control() && !matches!(character, '\n' | '\r' | '\t') => "\u{FFFD}".to_owned(),
character => character.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escape_xml_encodes_all_five_entities() {
assert_eq!(escape_xml("a&b<c>d\"e'f"), "a&b<c>d"e'f");
}
#[test]
fn escape_xml_character_replaces_control_characters_but_keeps_whitespace() {
assert_eq!(escape_xml_character('\u{07}'), "\u{FFFD}");
assert_eq!(escape_xml_character('\n'), "\n");
assert_eq!(escape_xml_character('\r'), "\r");
assert_eq!(escape_xml_character('\t'), "\t");
assert_eq!(escape_xml_character('x'), "x");
}
#[test]
fn escape_xml_body_bounded_reserves_marker_room_and_never_exceeds_budget() {
let marker = "\n[…truncated…]";
let budget = 40;
let output = escape_xml_body_bounded("&".repeat(40).as_str(), budget, marker);
assert!(output.ends_with(marker), "truncation must append the marker");
assert!(output.len() <= budget, "output {} exceeds {budget}", output.len());
let tiny = escape_xml_body_bounded("abcdef&ghijkl", 8, marker);
assert_eq!(tiny, marker);
}
#[test]
fn escape_xml_body_bounded_keeps_fully_fitting_input_untouched() {
let marker = "\n[…truncated…]";
assert_eq!(escape_xml_body_bounded("ab<cd", 64, marker), "ab<cd");
}
#[test]
fn escape_xml_attribute_matches_escape_xml() {
assert_eq!(escape_xml_attribute("a<b"), escape_xml("a<b"));
}
}