ansi_to_html/
esc.rs

1use std::fmt;
2
3/// A formatting wrapper for escaping HTML in a string.
4///
5/// The `Display` implementation replaces
6///   - `&` with `&`
7///   - `<` with `&lt;`
8///   - `>` with `&gt;`
9///   - `"` with `&quot;`
10///   - `'` with `&#39;`
11///
12/// `Esc` is lazy: If you don't use it, it does nothing. Also, it
13/// doesn't allocate a `String` unless you call `.to_string()`.
14///
15/// ## Examples
16///
17/// In a `format!`-like macro:
18///
19/// ```
20/// # use ansi_to_html::Esc;
21/// assert_eq!(&format!("{}", Esc("<h1>")), "&lt;h1&gt;");
22/// ```
23///
24/// Convert it to a String directly:
25///
26/// ```
27/// # use ansi_to_html::Esc;
28/// assert_eq!(&Esc("<h1>").to_string(), "&lt;h1&gt;");
29/// ```
30#[derive(Debug, Copy, Clone, Eq, PartialEq)]
31pub struct Esc<T: AsRef<str>>(pub T);
32
33impl<T: AsRef<str>> fmt::Display for Esc<T> {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        for c in self.0.as_ref().chars() {
36            match c {
37                '&' => fmt::Display::fmt("&amp;", f)?,
38                '<' => fmt::Display::fmt("&lt;", f)?,
39                '>' => fmt::Display::fmt("&gt;", f)?,
40                '"' => fmt::Display::fmt("&quot;", f)?,
41                '\'' => fmt::Display::fmt("&#39;", f)?,
42                c => fmt::Display::fmt(&c, f)?,
43            }
44        }
45        Ok(())
46    }
47}