use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UntrustedString(String);
impl UntrustedString {
pub fn new(s: String) -> Self {
UntrustedString(s)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for UntrustedString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug)]
pub struct SafeHtml(String);
impl SafeHtml {
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl fmt::Display for SafeHtml {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
pub struct Sanitizer;
impl Sanitizer {
pub fn encode(untrusted: UntrustedString) -> SafeHtml {
let encoded: String = untrusted
.0
.chars()
.map(|c| match c {
'&' => "&".to_string(),
'<' => "<".to_string(),
'>' => ">".to_string(),
'"' => """.to_string(),
'\'' => "'".to_string(),
'/' => "/".to_string(),
c => c.to_string(),
})
.collect();
SafeHtml(encoded)
}
pub fn trust(safe_str: &str) -> SafeHtml {
SafeHtml(safe_str.to_string())
}
}