MCPcopy Create free account
hub / github.com/buger/jsonparser / Unescape

Function Unescape

escape.go:253–300  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

251// Else:
252// A new slice is allocated and returned.
253func 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}

Callers 15

parseQuotedPathKeyFunction · 0.85
findKeyStartFunction · 0.85
searchKeysFunction · 0.85
EachKeyFunction · 0.85
EachKeyErrFunction · 0.85
ObjectEachFunction · 0.85
ParseStringFunction · 0.85
TestUnescapeFunction · 0.85

Calls 1

unescapeToUTF8Function · 0.85