]> git.proxmox.com Git - rustc.git/blame - src/tools/rustfmt/src/emitter/checkstyle/xml.rs
New upstream version 1.52.1+dfsg1
[rustc.git] / src / tools / rustfmt / src / emitter / checkstyle / xml.rs
CommitLineData
f20569fa
XL
1use std::fmt::{self, Display};
2
3/// Convert special characters into XML entities.
4/// This is needed for checkstyle output.
5pub(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, "&lt;"),
12 '>' => write!(formatter, "&gt;"),
13 '"' => write!(formatter, "&quot;"),
14 '\'' => write!(formatter, "&apos;"),
15 '&' => write!(formatter, "&amp;"),
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 "&lt;&gt;&quot;&apos;&amp;",
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 &quot;🦊&quot; jumps &lt;over&gt; 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}