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
use std::fmt;
/// A formatting wrapper for escaping HTML in a string.
///
/// The `Display` implementation replaces
/// - `&` with `&`
/// - `<` with `<`
/// - `>` with `>`
/// - `"` with `"`
/// - `'` with `'`
///
/// `Esc` is lazy: If you don't use it, it does nothing. Also, it
/// doesn't allocate a `String` unless you call `.to_string()`.
///
/// ## Examples
///
/// In a `format!`-like macro:
///
/// ```
/// # use ansi_to_html::Esc;
/// assert_eq!(format!("{}", Esc("<h1>")).as_str(), "<h1>");
/// ```
///
/// Convert it to a String directly:
///
/// ```
/// # use ansi_to_html::Esc;
/// assert_eq!(Esc("<h1>").to_string().as_str(), "<h1>");
/// ```
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Esc<T: AsRef<str>>(pub T);
impl<T: AsRef<str>> fmt::Display for Esc<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for c in self.0.as_ref().chars() {
match c {
'&' => fmt::Display::fmt("&", f)?,
'<' => fmt::Display::fmt("<", f)?,
'>' => fmt::Display::fmt(">", f)?,
'"' => fmt::Display::fmt(""", f)?,
'\'' => fmt::Display::fmt("'", f)?,
c => fmt::Display::fmt(&c, f)?,
}
}
Ok(())
}
}