unescapeChar takes a string input and returns the following info: value - the escaped unicode rune at the front of the string. encode - the value should be unicode-encoded tail - the remainder of the input string. err - error value, if the character could not be unescaped. When encode is true
(s string, isBytes bool)
| 102 | // If isBytes is set, unescape as a bytes literal so octal and hex escapes |
| 103 | // represent byte values, not unicode code points. |
| 104 | func unescapeChar(s string, isBytes bool) (value rune, encode bool, tail string, err error) { |
| 105 | // 1. Character is not an escape sequence. |
| 106 | switch c := s[0]; { |
| 107 | case c >= utf8.RuneSelf: |
| 108 | r, size := utf8.DecodeRuneInString(s) |
| 109 | return r, true, s[size:], nil |
| 110 | case c != '\\': |
| 111 | return rune(s[0]), false, s[1:], nil |
| 112 | } |
| 113 | |
| 114 | // 2. Last character is the start of an escape sequence. |
| 115 | if len(s) <= 1 { |
| 116 | err = errors.New("unable to unescape string, found '\\' as last character") |
| 117 | return |
| 118 | } |
| 119 | |
| 120 | c := s[1] |
| 121 | s = s[2:] |
| 122 | // 3. Common escape sequences shared with Google SQL |
| 123 | switch c { |
| 124 | case 'a': |
| 125 | value = '\a' |
| 126 | case 'b': |
| 127 | value = '\b' |
| 128 | case 'f': |
| 129 | value = '\f' |
| 130 | case 'n': |
| 131 | value = '\n' |
| 132 | case 'r': |
| 133 | value = '\r' |
| 134 | case 't': |
| 135 | value = '\t' |
| 136 | case 'v': |
| 137 | value = '\v' |
| 138 | case '\\': |
| 139 | value = '\\' |
| 140 | case '\'': |
| 141 | value = '\'' |
| 142 | case '"': |
| 143 | value = '"' |
| 144 | case '`': |
| 145 | value = '`' |
| 146 | case '?': |
| 147 | value = '?' |
| 148 | |
| 149 | // 4. Unicode escape sequences, reproduced from `strconv/quote.go` |
| 150 | case 'x', 'X', 'u', 'U': |
| 151 | n := 0 |
| 152 | encode = true |
| 153 | switch c { |
| 154 | case 'x', 'X': |
| 155 | n = 2 |
| 156 | encode = !isBytes |
| 157 | case 'u': |
| 158 | n = 4 |
| 159 | if isBytes { |
| 160 | err = errors.New("unable to unescape string") |
| 161 | return |