1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use core::fmt::{Formatter, Write};

pub struct HtmlEscaper<'a, 'b>(pub &'a mut Formatter<'b>);

impl Write for HtmlEscaper<'_, '_> {
  fn write_str(&mut self, s: &str) -> core::fmt::Result {
    let mut i = 0;
    for (j, c) in s.char_indices() {
      let replacement = match c {
        '"' => Some("&quot;"),
        '&' => Some("&amp;"),
        '\'' => Some("&#x39;"),
        '<' => Some("&lt;"),
        '>' => Some("&gt;"),
        _ => None,
      };
      if let Some(replacement) = replacement {
        if i < j {
          self.0.write_str(&s[i..j])?;
        }
        self.0.write_str(replacement)?;
        i = j + c.len_utf8();
      }
    }

    if i < s.len() {
      self.0.write_str(&s[i..])?;
    }

    Ok(())
  }
}

#[cfg(test)]
mod tests {
  use {
    super::*,
    core::fmt::{self, Display},
  };

  struct Wrapper(&'static str);

  impl Display for Wrapper {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
      write!(HtmlEscaper(f), "{}", self.0)
    }
  }

  #[test]
  fn unescaped_characters() {
    assert_eq!(Wrapper("hello").to_string(), "hello");
  }

  #[test]
  fn escaped_characters() {
    assert_eq!(Wrapper("\"").to_string(), "&quot;");
    assert_eq!(Wrapper("&").to_string(), "&amp;");
    assert_eq!(Wrapper("'").to_string(), "&#x39;");
    assert_eq!(Wrapper("<").to_string(), "&lt;");
    assert_eq!(Wrapper(">").to_string(), "&gt;");
  }

  #[test]
  fn mixed_characters() {
    assert_eq!(Wrapper("foo&bar&baz").to_string(), "foo&amp;bar&amp;baz");
  }
}