rustfmt_nightly/emitter/checkstyle/
xml.rs
1use std::fmt::{self, Display};
2
3pub(super) struct XmlEscaped<'a>(pub(super) &'a str);
6
7impl<'a> Display for XmlEscaped<'a> {
8 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
9 for char in self.0.chars() {
10 match char {
11 '<' => write!(formatter, "<"),
12 '>' => write!(formatter, ">"),
13 '"' => write!(formatter, """),
14 '\'' => write!(formatter, "'"),
15 '&' => write!(formatter, "&"),
16 _ => write!(formatter, "{char}"),
17 }?;
18 }
19
20 Ok(())
21 }
22}
23
24#[cfg(test)]
25mod tests {
26 use super::*;
27
28 #[test]
29 fn special_characters_are_escaped() {
30 assert_eq!(
31 "<>"'&",
32 format!("{}", XmlEscaped(r#"<>"'&"#)),
33 );
34 }
35
36 #[test]
37 fn special_characters_are_escaped_in_string_with_other_characters() {
38 assert_eq!(
39 "The quick brown "🦊" jumps <over> the lazy 🐶",
40 format!(
41 "{}",
42 XmlEscaped(r#"The quick brown "🦊" jumps <over> the lazy 🐶"#)
43 ),
44 );
45 }
46
47 #[test]
48 fn other_characters_are_not_escaped() {
49 let string = "The quick brown 🦊 jumps over the lazy 🐶";
50 assert_eq!(string, format!("{}", XmlEscaped(string)));
51 }
52}