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 `<`
8/// - `>` with `>`
9/// - `"` with `"`
10/// - `'` with `'`
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>")), "<h1>");
22/// ```
23///
24/// Convert it to a String directly:
25///
26/// ```
27/// # use ansi_to_html::Esc;
28/// assert_eq!(&Esc("<h1>").to_string(), "<h1>");
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("&", f)?,
38 '<' => fmt::Display::fmt("<", f)?,
39 '>' => fmt::Display::fmt(">", f)?,
40 '"' => fmt::Display::fmt(""", f)?,
41 '\'' => fmt::Display::fmt("'", f)?,
42 c => fmt::Display::fmt(&c, f)?,
43 }
44 }
45 Ok(())
46 }
47}