Skip to main content

escape

Function escape 

Source
pub fn escape(s: &str) -> String
Expand description

HTML-escapes a string for safe interpolation ({{ }}, not {!! !!}).

Every dynamic value in every rendered template passes through this - a genuinely hot path, so it’s worth not paying for what a naive per-char loop actually costs: a chars() iterator decodes each Unicode scalar and calls String::push (its own UTF-8 re-encode) even for the overwhelming majority of input that’s plain, nothing-to-escape text. Scanning s’s raw bytes instead and bulk-push_str-ing each unescaped run in one shot (rather than one push per character) means an all-plain-text value - the common case - costs one memcpy-shaped copy of the whole string, not N individual char pushes.

Byte-indexing here (not char_indices()) is safe only because every character this function ever escapes (&, <, >, ", ') is single-byte ASCII, and UTF-8 guarantees no byte belonging to a multi-byte sequence can ever equal a single-byte ASCII code point - so every index this loop slices s at is already guaranteed to sit on a real char boundary, never mid-sequence. This is not true in general for arbitrary byte values; if this function ever needs to escape a non-ASCII character, this approach would need revisiting.