unescape unescapes the string contained in 'in' and returns it as a slice. If 'in' contains no escaped characters: Returns 'in'. Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)): 'out' is used to build the unescaped string and is returned with no extra allocation Else: A
(in, out []byte)
| 251 | // Else: |
| 252 | // A new slice is allocated and returned. |
| 253 | func Unescape(in, out []byte) ([]byte, error) { |
| 254 | firstBackslash := bytes.IndexByte(in, '\\') |
| 255 | if firstBackslash == -1 { |
| 256 | return in, nil |
| 257 | } |
| 258 | |
| 259 | // Get a buffer of sufficient size (allocate if needed) |
| 260 | if cap(out) < len(in) { |
| 261 | out = make([]byte, len(in)) |
| 262 | } else { |
| 263 | out = out[0:len(in)] |
| 264 | } |
| 265 | |
| 266 | // Copy the first sequence of unescaped bytes to the output and obtain a buffer pointer (subslice) |
| 267 | copy(out, in[:firstBackslash]) |
| 268 | in = in[firstBackslash:] |
| 269 | buf := out[firstBackslash:] |
| 270 | |
| 271 | // The loop always exits via break: either on error (MalformedStringEscapeError) |
| 272 | // or after copying the final non-escaped tail. The former `for len(in) > 0` |
| 273 | // guard was structurally always true on re-entry since the else branch always |
| 274 | // leaves at least the backslash character in `in`. |
| 275 | for { |
| 276 | // Unescape the next escaped character |
| 277 | inLen, bufLen := unescapeToUTF8(in, buf) |
| 278 | if inLen == -1 { |
| 279 | return nil, MalformedStringEscapeError |
| 280 | } |
| 281 | |
| 282 | in = in[inLen:] |
| 283 | buf = buf[bufLen:] |
| 284 | |
| 285 | // Copy everything up until the next backslash |
| 286 | nextBackslash := bytes.IndexByte(in, '\\') |
| 287 | if nextBackslash == -1 { |
| 288 | copy(buf, in) |
| 289 | buf = buf[len(in):] |
| 290 | break |
| 291 | } else { |
| 292 | copy(buf, in[:nextBackslash]) |
| 293 | buf = buf[nextBackslash:] |
| 294 | in = in[nextBackslash:] |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // Trim the out buffer to the amount that was actually emitted |
| 299 | return out[:len(out)-len(buf)], nil |
| 300 | } |