Escape returns a Mangle source representation of a string. In !isBytes mode: - newlines are escaped as \n, tags as \t - other control characters [0x00..0x20] are byte-escaped, - Quote characters " and ' are character-escaped, - UTF8 sequences for code points > 0x80 are unicode-escaped. In isBytes mo
(str string, isBytes bool)
| 16 | // - all characters [0x00..0x20] and [0x80...0xFF] are byte-escaped. |
| 17 | // - quote characters " and ' are byte-escaped, |
| 18 | func Escape(str string, isBytes bool) (string, error) { |
| 19 | buf := make([]byte, 0, len(str)) |
| 20 | for len(str) > 0 { |
| 21 | c := str[0] |
| 22 | if c < utf8.RuneSelf { |
| 23 | switch c { |
| 24 | case '\'': |
| 25 | if isBytes { |
| 26 | buf = append(buf, `\x27`...) |
| 27 | } else { |
| 28 | buf = append(buf, `\'`...) |
| 29 | } |
| 30 | case '"': |
| 31 | if isBytes { |
| 32 | buf = append(buf, `\x22`...) |
| 33 | } else { |
| 34 | buf = append(buf, `\"`...) |
| 35 | } |
| 36 | case '\n': |
| 37 | if isBytes { |
| 38 | buf = append(buf, `\x0a`...) |
| 39 | } else { |
| 40 | buf = append(buf, `\n`...) |
| 41 | } |
| 42 | case '\t': |
| 43 | if isBytes { |
| 44 | buf = append(buf, `\x09`...) |
| 45 | } else { |
| 46 | buf = append(buf, `\t`...) |
| 47 | } |
| 48 | case '\\': |
| 49 | if isBytes { |
| 50 | buf = append(buf, `\x5c`...) |
| 51 | } else { |
| 52 | buf = append(buf, `\\`...) |
| 53 | } |
| 54 | default: |
| 55 | buf = append(buf, byte(c)) |
| 56 | } |
| 57 | str = str[1:] |
| 58 | continue |
| 59 | } |
| 60 | if isBytes { |
| 61 | buf = append(buf, `\x`...) |
| 62 | buf = append(buf, hexdigit(byte(c>>4))) |
| 63 | buf = append(buf, hexdigit(byte(c&0xf))) |
| 64 | str = str[1:] |
| 65 | continue |
| 66 | } |
| 67 | r, _, rest, err := unescapeCharPrefix(str, false) |
| 68 | if err != nil { |
| 69 | return "", err |
| 70 | } |
| 71 | if r == utf8.RuneError { |
| 72 | if len(str)-len(rest) == 1 { |
| 73 | return "", fmt.Errorf("invalid UTF-8 encoding") |
| 74 | } |
| 75 | } |