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

Function Unescape

escape.go:206–253  ·  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

204// Else:
205// A new slice is allocated and returned.
206func Unescape(in, out []byte) ([]byte, error) {
207 firstBackslash := bytes.IndexByte(in, '\\')
208 if firstBackslash == -1 {
209 return in, nil
210 }
211
212 // Get a buffer of sufficient size (allocate if needed)
213 if cap(out) < len(in) {
214 out = make([]byte, len(in))
215 } else {
216 out = out[0:len(in)]
217 }
218
219 // Copy the first sequence of unescaped bytes to the output and obtain a buffer pointer (subslice)
220 copy(out, in[:firstBackslash])
221 in = in[firstBackslash:]
222 buf := out[firstBackslash:]
223
224 // The loop always exits via break: either on error (MalformedStringEscapeError)
225 // or after copying the final non-escaped tail. The former `for len(in) > 0`
226 // guard was structurally always true on re-entry since the else branch always
227 // leaves at least the backslash character in `in`.
228 for {
229 // Unescape the next escaped character
230 inLen, bufLen := unescapeToUTF8(in, buf)
231 if inLen == -1 {
232 return nil, MalformedStringEscapeError
233 }
234
235 in = in[inLen:]
236 buf = buf[bufLen:]
237
238 // Copy everything up until the next backslash
239 nextBackslash := bytes.IndexByte(in, '\\')
240 if nextBackslash == -1 {
241 copy(buf, in)
242 buf = buf[len(in):]
243 break
244 } else {
245 copy(buf, in[:nextBackslash])
246 buf = buf[nextBackslash:]
247 in = in[nextBackslash:]
248 }
249 }
250
251 // Trim the out buffer to the amount that was actually emitted
252 return out[:len(out)-len(buf)], nil
253}

Callers 15

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

Calls 1

unescapeToUTF8Function · 0.85