MCPcopy Index your code
hub / github.com/expr-lang/expr / unescapeByteChar

Function unescapeByteChar

parser/lexer/utils.go:261–337  ·  view source on GitHub ↗

unescapeByteChar unescapes a single character or escape sequence from a bytes literal. Unlike unescapeChar, this only supports byte-level escapes (\x, octal) and rejects Unicode escapes (\u, \U) since bytes literals represent raw byte sequences. Note: We cannot use strconv.UnquoteChar here because

(s string)

Source from the content-addressed store, hash-verified

259// escapes as Unicode codepoints (e.g., \xff → codepoint 255 → 2 UTF-8 bytes),
260// whereas bytes literals require them as raw byte values (\xff → single byte 255).
261func unescapeByteChar(s string) (value rune, multibyte bool, tail string, err error) {
262 // Non-escape: return the character as-is.
263 // For bytes literals, we accept UTF-8 sequences but they get encoded back to bytes.
264 c := s[0]
265 if c != '\\' {
266 if c >= utf8.RuneSelf {
267 r, size := utf8.DecodeRuneInString(s)
268 return r, true, s[size:], nil
269 }
270 return rune(c), false, s[1:], nil
271 }
272
273 // Escape sequence: need at least one more character.
274 if len(s) <= 1 {
275 return 0, false, "", fmt.Errorf("unable to unescape string, found '\\' as last character")
276 }
277
278 c = s[1]
279 s = s[2:]
280
281 switch c {
282 // Simple escape sequences
283 case 'a':
284 return '\a', false, s, nil
285 case 'b':
286 return '\b', false, s, nil
287 case 'f':
288 return '\f', false, s, nil
289 case 'n':
290 return '\n', false, s, nil
291 case 'r':
292 return '\r', false, s, nil
293 case 't':
294 return '\t', false, s, nil
295 case 'v':
296 return '\v', false, s, nil
297 case '\\':
298 return '\\', false, s, nil
299 case '\'':
300 return '\'', false, s, nil
301 case '"':
302 return '"', false, s, nil
303 case '`':
304 return '`', false, s, nil
305 case '?':
306 return '?', false, s, nil
307
308 // Hex escape: \xNN (exactly 2 hex digits, value 0-255)
309 case 'x', 'X':
310 if len(s) < 2 {
311 return 0, false, "", fmt.Errorf("unable to unescape string")
312 }
313 hi, ok1 := unhex(s[0])
314 lo, ok2 := unhex(s[1])
315 if !ok1 || !ok2 {
316 return 0, false, "", fmt.Errorf("unable to unescape string")
317 }
318 return hi<<4 | lo, false, s[2:], nil

Callers 1

unescapeBytesFunction · 0.85

Calls 2

unhexFunction · 0.85
ErrorfMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…