Skip to main content

hemplate_runtime/
escape.rs

1//! HTML escaping utility.
2
3use core::fmt::{self, Write as _};
4
5/// Wrapper that HTML-escapes the Display output of the inner value.
6pub 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("&amp;")?,
21                '<' => self.0.write_str("&lt;")?,
22                '>' => self.0.write_str("&gt;")?,
23                '"' => self.0.write_str("&quot;")?,
24                '\'' => self.0.write_str("&#x27;")?,
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&amp;b");
56    }
57
58    #[test]
59    fn escapes_angle_brackets() {
60        assert_eq!(HtmlEscape("<div>").to_string(), "&lt;div&gt;");
61    }
62
63    #[test]
64    fn escapes_quotes() {
65        assert_eq!(HtmlEscape(r#"a"b'c"#).to_string(), "a&quot;b&#x27;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            "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"
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}