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)
| 133 | // Else: |
| 134 | // A new slice is allocated and returned. |
| 135 | func Unescape(in, out []byte) ([]byte, error) { |
| 136 | firstBackslash := bytes.IndexByte(in, '\\') |
| 137 | if firstBackslash == -1 { |
| 138 | return in, nil |
| 139 | } |
| 140 | |
| 141 | // Get a buffer of sufficient size (allocate if needed) |
| 142 | if cap(out) < len(in) { |
| 143 | out = make([]byte, len(in)) |
| 144 | } else { |
| 145 | out = out[0:len(in)] |
| 146 | } |
| 147 | |
| 148 | // Copy the first sequence of unescaped bytes to the output and obtain a buffer pointer (subslice) |
| 149 | copy(out, in[:firstBackslash]) |
| 150 | in = in[firstBackslash:] |
| 151 | buf := out[firstBackslash:] |
| 152 | |
| 153 | // The loop always exits via break: either on error (MalformedStringEscapeError) |
| 154 | // or after copying the final non-escaped tail. The former `for len(in) > 0` |
| 155 | // guard was structurally always true on re-entry since the else branch always |
| 156 | // leaves at least the backslash character in `in`. |
| 157 | for { |
| 158 | // Unescape the next escaped character |
| 159 | inLen, bufLen := unescapeToUTF8(in, buf) |
| 160 | if inLen == -1 { |
| 161 | return nil, MalformedStringEscapeError |
| 162 | } |
| 163 | |
| 164 | in = in[inLen:] |
| 165 | buf = buf[bufLen:] |
| 166 | |
| 167 | // Copy everything up until the next backslash |
| 168 | nextBackslash := bytes.IndexByte(in, '\\') |
| 169 | if nextBackslash == -1 { |
| 170 | copy(buf, in) |
| 171 | buf = buf[len(in):] |
| 172 | break |
| 173 | } else { |
| 174 | copy(buf, in[:nextBackslash]) |
| 175 | buf = buf[nextBackslash:] |
| 176 | in = in[nextBackslash:] |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // Trim the out buffer to the amount that was actually emitted |
| 181 | return out[:len(out)-len(buf)], nil |
| 182 | } |
searching dependent graphs…