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