hemplate_runtime/
escape.rs1use core::fmt::{self, Write as _};
4
5pub struct HtmlEscape<T: fmt::Display>(pub T);
7
8impl<T: fmt::Display> fmt::Display for HtmlEscape<T> {
9 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
10 write!(EscapeWriter(formatter), "{}", self.0)
11 }
12}
13
14struct EscapeWriter<'formatter, 'buffer>(&'formatter mut fmt::Formatter<'buffer>);
15
16impl fmt::Write for EscapeWriter<'_, '_> {
17 fn write_str(&mut self, text: &str) -> fmt::Result {
18 for character in text.chars() {
19 match character {
20 '&' => self.0.write_str("&")?,
21 '<' => self.0.write_str("<")?,
22 '>' => self.0.write_str(">")?,
23 '"' => self.0.write_str(""")?,
24 '\'' => self.0.write_str("'")?,
25 safe => self.0.write_char(safe)?,
26 }
27 }
28 Ok(())
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35 use alloc::string::{String, ToString};
36
37 struct FailingWriter;
38
39 impl fmt::Write for FailingWriter {
40 fn write_str(&mut self, _text: &str) -> fmt::Result {
41 Err(fmt::Error)
42 }
43 }
44
45 struct FailingDisplay;
46
47 impl fmt::Display for FailingDisplay {
48 fn fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49 Err(fmt::Error)
50 }
51 }
52
53 #[test]
54 fn escapes_ampersand() {
55 assert_eq!(HtmlEscape("a&b").to_string(), "a&b");
56 }
57
58 #[test]
59 fn escapes_angle_brackets() {
60 assert_eq!(HtmlEscape("<div>").to_string(), "<div>");
61 }
62
63 #[test]
64 fn escapes_quotes() {
65 assert_eq!(HtmlEscape(r#"a"b'c"#).to_string(), "a"b'c");
66 }
67
68 #[test]
69 fn passes_through_safe_text() {
70 assert_eq!(HtmlEscape("hello world").to_string(), "hello world");
71 }
72
73 #[test]
74 fn escapes_all_special_chars() {
75 assert_eq!(
76 HtmlEscape(r#"<script>alert("xss")</script>"#).to_string(),
77 "<script>alert("xss")</script>"
78 );
79 }
80
81 #[test]
82 fn propagates_input_display_failure() {
83 assert!(write!(&mut String::new(), "{}", HtmlEscape(FailingDisplay)).is_err());
84 }
85
86 #[test]
87 fn propagates_output_failure_for_escaped_and_safe_characters() {
88 for text in ["&", "<", ">", "\"", "'", "safe"] {
89 assert!(write!(&mut FailingWriter, "{}", HtmlEscape(text)).is_err());
90 }
91 }
92}