Skip to main content

gen_html/
escape.rs

1use crate::Render;
2use std::fmt;
3
4pub(crate) fn escape(s: &str, f: &mut fmt::Formatter) -> fmt::Result {
5    use fmt::Write;
6
7    for ch in s.chars() {
8        match ch {
9            '&' => write!(f, "&")?,
10            '<' => write!(f, "&lt;")?,
11            '>' => write!(f, "&gt;")?,
12            '"' => write!(f, "&quot;")?,
13            ch => f.write_char(ch)?,
14        }
15    }
16
17    Ok(())
18}
19
20/// Wrapper that escapes HTML special characters.
21///
22/// The following characters are escaped:
23/// - `&` ==> `&amp;`
24/// - `<` ==> `&lt;`
25/// - `>` ==> `&gt;`
26/// - `"` ==> `&quot;`
27///
28/// # Example
29///
30/// ```
31/// use gen_html::Escaped;
32/// assert_eq!(Escaped("&<>\"").to_string(), "&amp;&lt;&gt;&quot;")
33/// ```
34#[derive(Debug, Clone, Copy)]
35pub struct Escaped<T>(pub T);
36
37impl<T: fmt::Display> fmt::Display for Escaped<T> {
38    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39        escape(&self.0.to_string(), f)
40    }
41}
42
43impl<T: fmt::Display> Render for Escaped<T> {
44    fn render_to(&self, f: &mut fmt::Formatter) -> fmt::Result {
45        escape(&self.0.to_string(), f)
46    }
47}