pub fn escape_html_attr(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => escaped.push_str("&"),
'<' => escaped.push_str("<"),
'>' => escaped.push_str(">"),
'"' => escaped.push_str("""),
'\'' => escaped.push_str("'"),
_ => escaped.push(ch),
}
}
escaped
}
pub fn escape_markdown_link_text(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'\\' | '[' | ']' => {
escaped.push('\\');
escaped.push(ch);
}
_ => escaped.push(ch),
}
}
escaped
}
pub fn escape_markdown_link_destination(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'\\' | '(' | ')' | ' ' => {
escaped.push('\\');
escaped.push(ch);
}
_ => escaped.push(ch),
}
}
escaped
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_escape_html_attr() {
assert_eq!(
escape_html_attr("a\"b<c>d&e'"),
"a"b<c>d&e'"
);
}
#[test]
fn test_escape_markdown_link_text() {
assert_eq!(escape_markdown_link_text("A[B]"), "A\\[B\\]");
}
#[test]
fn test_escape_markdown_link_destination() {
assert_eq!(
escape_markdown_link_destination("https://x.y/a b(c)"),
"https://x.y/a\\ b\\(c\\)"
);
}
}