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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
//! # Functions to escape raw text into HTML
use paste::paste;
use std::borrow::Cow;
/// Find a `u8` in a slice. You may specify as many bytes to search for as you
/// want. If you are searching for 3 or fewer bytes, this will use [`memchr`].
macro_rules! find_u8_body {
($slice:expr, $ch1:literal $(,)?) => {
memchr::memchr($ch1, $slice)
};
($slice:expr, $ch1:literal, $ch2:literal $(,)?) => {
memchr::memchr2($ch1, $ch2, $slice)
};
($slice:expr, $ch1:literal, $ch2:literal, $ch3:literal $(,)?) => {
memchr::memchr3($ch1, $ch2, $ch3, $slice)
};
($slice:expr, $($ch:literal),+) => {
$slice.iter().position(|c| matches!(c, $($ch)|+))
};
}
/// Generate string and byte string versions of an escape function.
macro_rules! escape_fn {
(
$(#[$meta:meta])*
$vis:vis fn $name:ident;
$(#[$bytes_meta:meta])*
$bytes_vis:vis fn $bytes_name:ident;
{
$($ch:literal => $entity:literal,)+
}
) => {
paste! {
$(#[$meta])*
$vis fn $name<'a, S: Into<Cow<'a, str>>>(input: S) -> Cow<'a, str> {
let input = input.into();
match [<$name _bytes_internal>](input.as_bytes()) {
Some(output) => String::from_utf8(output).unwrap().into(),
None => input,
}
}
$(#[$bytes_meta])*
$bytes_vis fn $bytes_name<'a, S: Into<Cow<'a, [u8]>>>(input: S) -> Cow<'a, [u8]> {
let input = input.into();
match [<$name _bytes_internal>](&*input) {
Some(output) => output.into(),
None => input,
}
}
#[inline(always)]
fn [<$name _bytes_internal>](raw: &[u8]) -> Option<Vec<u8>> {
#[inline]
fn find_u8(haystack: &[u8]) -> Option<usize> {
find_u8_body!(haystack, $($ch),+)
}
#[inline]
const fn map_u8(c: u8) -> &'static [u8] {
match c {
$( $ch => $entity, )+
// This should never happen, but using unreachable!()
// actually makes other parts of the function slower.
_ => b"",
}
}
if let Some(i) = find_u8(raw) {
let mut output: Vec<u8> = Vec::with_capacity(raw.len().saturating_mul(2));
output.extend_from_slice(&raw[..i]);
output.extend_from_slice(map_u8(raw[i]));
// i is a valid index, so it can't be usize::MAX.
debug_assert!(i < usize::MAX);
#[allow(clippy::arithmetic_side_effects)]
let mut remainder = &raw[i+1..];
while let Some(i) = find_u8(remainder) {
output.extend_from_slice(&remainder[..i]);
output.extend_from_slice(map_u8(remainder[i]));
// i is a valid index, so it can't be usize::MAX.
debug_assert!(i < usize::MAX);
#[allow(clippy::arithmetic_side_effects)]
let n = i + 1; // Work around https://github.com/rust-lang/rust/issues/15701
remainder = &remainder[n..];
}
output.extend_from_slice(&remainder);
Some(output)
} else {
None
}
}
}
}
}
escape_fn! {
/// Escape a string used in a text node, i.e. regular text.
///
/// **Do not use this in attributes.**
///
/// ```rust
/// use htmlize::escape_text;
///
/// assert_eq!(
/// escape_text(r#"Björk & Борис O'Brien <3, "love > hate""#),
/// r#"Björk & Борис O'Brien <3, "love > hate""#
/// );
/// ```
///
/// To work with bytes (`[u8]`) instead of strings, see
/// [`escape_text_bytes()`].
pub fn escape_text;
/// Escape a byte string used in a text node, i.e. regular text.
///
/// **Do not use this in attributes.**
///
/// ```rust
/// use htmlize::escape_text_bytes;
///
/// assert_eq!(
/// escape_text_bytes(b"test: &<>\"'".as_slice()),
/// b"test: &<>\"'".as_slice()
/// );
/// ```
///
/// To work with `String` instead of bytes, see [`escape_text()`].
pub fn escape_text_bytes;
{
b'&' => b"&",
b'<' => b"<",
b'>' => b">",
}
}
escape_fn! {
/// Escape a string to be used in a quoted attribute.
///
/// ```rust
/// use htmlize::escape_attribute;
///
/// assert_eq!(
/// escape_attribute(r#"Björk & Борис O'Brien <3, "love > hate""#),
/// "Björk & Борис O'Brien <3, "love > hate""
/// );
/// ```
///
/// To work with bytes (`[u8]`) instead of strings, see
/// [`escape_attribute_bytes()`].
pub fn escape_attribute;
/// Escape a byte string to be used in a quoted attribute.
///
/// ```rust
/// use htmlize::escape_attribute_bytes;
///
/// assert_eq!(
/// escape_attribute_bytes(b"test: &<>\"'".as_slice()),
/// b"test: &<>"'".as_slice()
/// );
/// ```
///
/// To work with `String` instead of bytes, see [`escape_attribute()`].
pub fn escape_attribute_bytes;
{
b'&' => b"&",
b'<' => b"<",
b'>' => b">",
b'"' => b""", // Attributes
}
}
escape_fn! {
/// Escape a string including both single and double quotes.
///
/// Generally, it is safe to leave single quotes (apostrophes) unescaped, so you
/// should use [`escape_text()`] or [`escape_attribute()`].
///
/// ```rust
/// use htmlize::escape_all_quotes;
///
/// assert_eq!(
/// escape_all_quotes(r#"Björk & Борис O'Brien <3, "love > hate""#),
/// "Björk & Борис O'Brien <3, "love > hate""
/// );
/// ```
///
/// To work with bytes (`[u8]`) instead of strings, see
/// [`escape_all_quotes_bytes()`].
pub fn escape_all_quotes;
/// Escape a byte string including both single and double quotes.
///
/// Generally, it is safe to leave single quotes (apostrophes) unescaped, so you
/// should use [`escape_text_bytes()`] or [`escape_attribute_bytes()`].
///
/// ```rust
/// use htmlize::escape_all_quotes_bytes;
///
/// assert_eq!(
/// escape_all_quotes_bytes(b"test: &<>\"'".as_slice()),
/// b"test: &<>"'".as_slice()
/// );
/// ```
///
/// To work with `String` instead of bytes, see [`escape_all_quotes()`].
pub fn escape_all_quotes_bytes;
{
b'&' => b"&",
b'<' => b"<",
b'>' => b">",
b'"' => b""", // Attributes
b'\'' => b"'", // Single quoted attributes
}
}
#[cfg(test)]
mod tests {
use super::*;
use assert2::assert;
use paste::paste;
macro_rules! test {
($name:ident, $($test:tt)+) => {
#[test]
fn $name() {
#![allow(clippy::string_lit_as_bytes)]
assert!($($test)+);
}
};
}
// Test all escape functions
macro_rules! test_all {
($name:ident, $in:expr, $out:expr) => {
paste! {
test!([<escape_text_ $name>], escape_text($in) == $out);
test!(
[<escape_attribute_ $name>],
escape_attribute($in) == $out
);
test!(
[<escape_all_quotes_ $name>],
escape_all_quotes($in) == $out
);
test!(
[<escape_text_bytes_ $name>],
escape_text_bytes($in.as_bytes()) == $out.as_bytes()
);
test!(
[<escape_attribute_bytes_ $name>],
escape_attribute_bytes($in.as_bytes()) == $out.as_bytes()
);
test!(
[<escape_all_quotes_bytes_ $name>],
escape_all_quotes_bytes($in.as_bytes()) == $out.as_bytes()
);
}
};
}
test_all!(none, "", "");
test_all!(clean, "clean", "clean");
test_all!(lt_gt, "< >", "< >");
test_all!(amp, "&", "&amp;");
test_all!(prefix_amp, "prefix&", "prefix&");
test_all!(emoji_amp, "☺️&☺️", "☺️&☺️");
test_all!(
special_clean,
"Björk and Борис OBrien ❤️, “love beats hate”",
"Björk and Борис OBrien ❤️, “love beats hate”"
);
test!(
escape_text_quotes,
escape_text("He said, \"That's mine.\"") == "He said, \"That's mine.\""
);
test!(
escape_attribute_quotes,
escape_attribute("He said, \"That's mine.\"")
== "He said, "That's mine.""
);
test!(
escape_all_quotes_quotes,
escape_all_quotes("He said, \"That's mine.\"")
== "He said, "That's mine.""
);
test!(
escape_all_quotes_bytes_quotes,
&*escape_all_quotes_bytes(&b"He said, \"That's mine.\""[..])
== b"He said, "That's mine.""
);
test!(
escape_text_bytes_quotes,
&*escape_text_bytes(&b"He said, \"That's mine.\""[..])
== b"He said, \"That's mine.\""
);
test!(
escape_attribute_bytes_quotes,
&*escape_attribute_bytes(&b"He said, \"That's mine.\""[..])
== b"He said, "That's mine.""
);
const HTML_DIRTY: &str = include_str!("../tests/corpus/html-raw.txt");
const HTML_DIRTY_ESCAPED: &str =
include_str!("../tests/corpus/html-escaped.txt");
const HTML_CLEAN: &str = include_str!("../tests/corpus/html-cleaned.txt");
test!(
escape_text_dirty_html,
escape_text(HTML_DIRTY) == HTML_DIRTY_ESCAPED
);
test!(
escape_text_clean_html,
escape_text(HTML_CLEAN) == HTML_CLEAN
);
test!(
escape_text_bytes_dirty_html,
escape_text_bytes(HTML_DIRTY.as_bytes())
== HTML_DIRTY_ESCAPED.as_bytes()
);
test!(
escape_text_bytes_clean_html,
escape_text_bytes(HTML_CLEAN.as_bytes()) == HTML_CLEAN.as_bytes()
);
test!(
escape_text_bytes_invalid_utf8,
escape_text_bytes(&b"\xa1"[..]) == &b"\xa1"[..]
);
test!(
escape_attribute_bytes_invalid_utf8,
escape_attribute_bytes(&b"\xa1"[..]) == &b"\xa1"[..]
);
test!(
escape_all_quotes_bytes_invalid_utf8,
escape_all_quotes_bytes(&b"\xa1"[..]) == &b"\xa1"[..]
);
}