pub fn html(input: &str) -> String {
if !input.contains(['"', '\'', '<', '>', '&']) {
return String::from(input);
}
let mut escaped = String::with_capacity(input.len());
for c in input.chars() {
match c {
'"' => escaped.push_str("""),
'\'' => escaped.push_str("'"),
'&' => escaped.push_str("&"),
'<' => escaped.push_str("<"),
'>' => escaped.push_str(">"),
c => {
let mut buf = [0; 4];
escaped.push_str(c.encode_utf8(&mut buf));
}
}
}
escaped
}
pub fn attr(value: &str) -> String {
if !value.contains('"') {
return value.into();
}
value.replace('"', """)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encoding_html() {
assert_eq!(
html("Hello<>\"'&world;"),
"Hello<>"'&world;"
);
}
#[test]
fn encoding_attributes() {
assert_eq!(attr("some\"attribute"), "some"attribute");
}
}