Skip to main content

luaur_common/functions/
escape.rs

1use crate::functions::format_append::formatAppend;
2use alloc::string::String;
3
4pub fn escape(s: &str, escape_for_interp_string: bool) -> String {
5    let mut r = String::with_capacity(s.len() + 50);
6
7    for &c in s.as_bytes() {
8        if c >= b' ' && c != b'\\' && c != b'\'' && c != b'\"' && c != b'`' && c != b'{' {
9            r.push(c as char);
10        } else {
11            r.push('\\');
12
13            if escape_for_interp_string && (c == b'`' || c == b'{') {
14                r.push(c as char);
15                continue;
16            }
17
18            match c {
19                7 => r.push('a'),  // \a
20                8 => r.push('b'),  // \b
21                12 => r.push('f'), // \f
22                10 => r.push('n'), // \n
23                13 => r.push('r'), // \r
24                9 => r.push('t'),  // \t
25                11 => r.push('v'), // \v
26                b'\'' => r.push('\''),
27                b'\"' => r.push('\"'),
28                b'\\' => r.push('\\'),
29                // Upstream emits `%03u` (zero-padded, width 3) via `formatAppend`.
30                _ => formatAppend(&mut r, format_args!("{:03}", c)),
31            }
32        }
33    }
34
35    r
36}