1
+ use std:: fmt:: { self , Display } ;
1
2
use std:: io:: { self , Write } ;
2
3
use std:: path:: Path ;
3
4
@@ -35,13 +36,12 @@ where
35
36
for mismatch in diff {
36
37
for line in mismatch. lines {
37
38
// Do nothing with `DiffLine::Context` and `DiffLine::Resulting`.
38
- if let DiffLine :: Expected ( ref str) = line {
39
- let message = xml_escape_str ( str) ;
39
+ if let DiffLine :: Expected ( message) = line {
40
40
write ! (
41
41
writer,
42
42
"<error line=\" {}\" severity=\" warning\" message=\" Should be `{}`\" \
43
43
/>",
44
- mismatch. line_number, message
44
+ mismatch. line_number, XmlEscaped ( & message)
45
45
) ?;
46
46
}
47
47
}
@@ -50,19 +50,53 @@ where
50
50
Ok ( ( ) )
51
51
}
52
52
53
- // Convert special characters into XML entities.
54
- // This is needed for checkstyle output.
55
- fn xml_escape_str ( string : & str ) -> String {
56
- let mut out = String :: new ( ) ;
57
- for c in string. chars ( ) {
58
- match c {
59
- '<' => out. push_str ( "<" ) ,
60
- '>' => out. push_str ( ">" ) ,
61
- '"' => out. push_str ( """ ) ,
62
- '\'' => out. push_str ( "'" ) ,
63
- '&' => out. push_str ( "&" ) ,
64
- _ => out. push ( c) ,
53
+ /// Convert special characters into XML entities.
54
+ /// This is needed for checkstyle output.
55
+ struct XmlEscaped < ' a > ( & ' a str ) ;
56
+
57
+ impl < ' a > Display for XmlEscaped < ' a > {
58
+ fn fmt ( & self , formatter : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
59
+ for char in self . 0 . chars ( ) {
60
+ match char {
61
+ '<' => write ! ( formatter, "<" ) ,
62
+ '>' => write ! ( formatter, ">" ) ,
63
+ '"' => write ! ( formatter, """ ) ,
64
+ '\'' => write ! ( formatter, "'" ) ,
65
+ '&' => write ! ( formatter, "&" ) ,
66
+ _ => write ! ( formatter, "{}" , char ) ,
67
+ } ?;
65
68
}
69
+
70
+ Ok ( ( ) )
71
+ }
72
+ }
73
+
74
+ #[ cfg( test) ]
75
+ mod tests {
76
+ use super :: * ;
77
+
78
+ #[ test]
79
+ fn special_characters_are_escaped ( ) {
80
+ assert_eq ! (
81
+ "<>"'&" ,
82
+ format!( "{}" , XmlEscaped ( r#"<>"'&"# ) ) ,
83
+ ) ;
84
+ }
85
+
86
+ #[ test]
87
+ fn special_characters_are_escaped_in_string_with_other_characters ( ) {
88
+ assert_eq ! (
89
+ "The quick brown "🦊" jumps <over> the lazy 🐶" ,
90
+ format!(
91
+ "{}" ,
92
+ XmlEscaped ( r#"The quick brown "🦊" jumps <over> the lazy 🐶"# )
93
+ ) ,
94
+ ) ;
95
+ }
96
+
97
+ #[ test]
98
+ fn other_characters_are_not_escaped ( ) {
99
+ let string = "The quick brown 🦊 jumps over the lazy 🐶" ;
100
+ assert_eq ! ( string, format!( "{}" , XmlEscaped ( string) ) , ) ;
66
101
}
67
- out
68
102
}
0 commit comments