vtcode_commons/
untrusted_xml.rs1pub fn escape_xml_attribute(value: &str) -> String {
17 escape_xml(value)
18}
19
20pub fn escape_xml_body_bounded(value: &str, max_bytes: usize, truncation_marker: &str) -> String {
25 let marker = truncation_marker.as_bytes();
26 let mut output = String::with_capacity(value.len().min(max_bytes));
27 let mut truncated = false;
28
29 for character in value.chars() {
30 let escaped = escape_xml_character(character);
31 if output.len().saturating_add(escaped.len()).saturating_add(marker.len()) > max_bytes {
32 truncated = true;
33 break;
34 }
35 output.push_str(&escaped);
36 }
37
38 if truncated {
39 output.push_str(truncation_marker);
40 }
41 output
42}
43
44pub fn escape_xml(value: &str) -> String {
46 let mut output = String::with_capacity(value.len());
47 for character in value.chars() {
48 output.push_str(&escape_xml_character(character));
49 }
50 output
51}
52
53pub fn escape_xml_character(character: char) -> String {
58 match character {
59 '&' => "&".to_owned(),
60 '<' => "<".to_owned(),
61 '>' => ">".to_owned(),
62 '"' => """.to_owned(),
63 '\'' => "'".to_owned(),
64 character if character.is_control() && !matches!(character, '\n' | '\r' | '\t') => "\u{FFFD}".to_owned(),
65 character => character.to_string(),
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn escape_xml_encodes_all_five_entities() {
75 assert_eq!(escape_xml("a&b<c>d\"e'f"), "a&b<c>d"e'f");
76 }
77
78 #[test]
79 fn escape_xml_character_replaces_control_characters_but_keeps_whitespace() {
80 assert_eq!(escape_xml_character('\u{07}'), "\u{FFFD}");
81 assert_eq!(escape_xml_character('\n'), "\n");
82 assert_eq!(escape_xml_character('\r'), "\r");
83 assert_eq!(escape_xml_character('\t'), "\t");
84 assert_eq!(escape_xml_character('x'), "x");
85 }
86
87 #[test]
88 fn escape_xml_body_bounded_reserves_marker_room_and_never_exceeds_budget() {
89 let marker = "\n[…truncated…]";
90 let budget = 40;
91 let output = escape_xml_body_bounded("&".repeat(40).as_str(), budget, marker);
92 assert!(output.ends_with(marker), "truncation must append the marker");
93 assert!(output.len() <= budget, "output {} exceeds {budget}", output.len());
94 let tiny = escape_xml_body_bounded("abcdef&ghijkl", 8, marker);
97 assert_eq!(tiny, marker);
98 }
99
100 #[test]
101 fn escape_xml_body_bounded_keeps_fully_fitting_input_untouched() {
102 let marker = "\n[…truncated…]";
103 assert_eq!(escape_xml_body_bounded("ab<cd", 64, marker), "ab<cd");
104 }
105
106 #[test]
107 fn escape_xml_attribute_matches_escape_xml() {
108 assert_eq!(escape_xml_attribute("a<b"), escape_xml("a<b"));
109 }
110}