Unescape takes a quoted string, unquotes, and unescapes it. This function performs escaping compatible with GoogleSQL.
(value string, isBytes bool)
| 24 | // |
| 25 | // This function performs escaping compatible with GoogleSQL. |
| 26 | func unescape(value string, isBytes bool) (string, error) { |
| 27 | // All strings normalize newlines to the \n representation. |
| 28 | value = newlineNormalizer.Replace(value) |
| 29 | n := len(value) |
| 30 | |
| 31 | // Nothing to unescape / decode. |
| 32 | if n < 2 { |
| 33 | return value, errors.New("unable to unescape string") |
| 34 | } |
| 35 | |
| 36 | // Raw string preceded by the 'r|R' prefix. |
| 37 | isRawLiteral := false |
| 38 | if value[0] == 'r' || value[0] == 'R' { |
| 39 | value = value[1:] |
| 40 | n = len(value) |
| 41 | isRawLiteral = true |
| 42 | } |
| 43 | |
| 44 | // Quoted string of some form, must have same first and last char. |
| 45 | if value[0] != value[n-1] || (value[0] != '"' && value[0] != '\'') { |
| 46 | return value, errors.New("unable to unescape string") |
| 47 | } |
| 48 | |
| 49 | // Normalize the multi-line CEL string representation to a standard |
| 50 | // Go quoted string. |
| 51 | if n >= 6 { |
| 52 | if strings.HasPrefix(value, "'''") { |
| 53 | if !strings.HasSuffix(value, "'''") { |
| 54 | return value, errors.New("unable to unescape string") |
| 55 | } |
| 56 | value = "\"" + value[3:n-3] + "\"" |
| 57 | } else if strings.HasPrefix(value, `"""`) { |
| 58 | if !strings.HasSuffix(value, `"""`) { |
| 59 | return value, errors.New("unable to unescape string") |
| 60 | } |
| 61 | value = "\"" + value[3:n-3] + "\"" |
| 62 | } |
| 63 | n = len(value) |
| 64 | } |
| 65 | value = value[1 : n-1] |
| 66 | // If there is nothing to escape, then return. |
| 67 | if isRawLiteral || !strings.ContainsRune(value, '\\') { |
| 68 | return value, nil |
| 69 | } |
| 70 | |
| 71 | // Otherwise the string contains escape characters. |
| 72 | // The following logic is adapted from `strconv/quote.go` |
| 73 | var runeTmp [utf8.UTFMax]byte |
| 74 | buf := make([]byte, 0, 3*n/2) |
| 75 | for len(value) > 0 { |
| 76 | c, encode, rest, err := unescapeChar(value, isBytes) |
| 77 | if err != nil { |
| 78 | return "", err |
| 79 | } |
| 80 | value = rest |
| 81 | if c < utf8.RuneSelf || !encode { |
| 82 | buf = append(buf, byte(c)) |
| 83 | } else { |