use std::fmt;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct SafeHtml(String);
impl SafeHtml {
pub fn from_trusted(html: impl Into<String>) -> Self {
SafeHtml(html.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl fmt::Display for SafeHtml {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for SafeHtml {
fn as_ref(&self) -> &str {
&self.0
}
}
impl From<SafeHtml> for String {
fn from(html: SafeHtml) -> String {
html.0
}
}
pub fn escape_html(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(ch),
}
}
out
}
pub(crate) fn truncate_chars(text: &str, max: usize) -> &str {
match text.char_indices().nth(max) {
Some((index, _)) => &text[..index],
None => text,
}
}