Debian Codegraph @

internal/decoder/context.go

raw
1 package decoder
2
3 import (
4 "math/bits"
5 "reflect"
6 "sync"
7 "unsafe"
8
9 "github.com/goccy/go-json/internal/errors"
10 "github.com/goccy/go-json/internal/runtime"
11 )
12
13 type RuntimeContext struct {
14 Buf []byte
15 Option *Option
16 // slot is where a value of interface{} is decoded before it is put into a map or a slice.
17 // The decoders of the values nested in it use it too: each of them takes the value out of it
18 // before the next value is decoded, and puts its own value into it only at its end.
19 slot any
20 // anyStack holds the elements of the arrays being decoded into []interface{}: an array pushes
21 // its elements above the ones of the arrays it is nested in, and pops them at its end. The objects
22 // being decoded into new maps of map[string]interface{} push their entries to entryStack, a key and its
23 // value at once, so that a map is made of the size of its object ( see decodeNewStringAnyMap ).
24 anyStack []any
25 entryStack []anyEntry
26 // floats and strings are the slabs in which the numbers and the strings decoded into interface{}
27 // are kept, so that an interface value refers to them without an allocation of its own.
28 // A slot of a slab is never written again once an interface value refers to it.
29 floats []float64
30 strings []string
31 // input is the buffer which the input of Unmarshal is copied to, followed by a nul byte. It is reused by
32 // the calls: nothing decoded refers to it, because the decoded strings are copied out of it ( makeString ).
33 input []byte
34 // origin is the input of the call when Buf is the reused copy of it, at the same offsets: the decoded strings
35 // are copied, or refer to origin under NoCopyStringOption. It is nil when Buf is never written again after the
36 // value is decoded, as the buffer of a stream: the strings refer to Buf then.
37 origin []byte
38 // arena is where the bytes of the decoded strings are copied to. A string refers to a part of it which is
39 // never written again, so the arena is kept from a call to the next, as the slab of floats.
40 arena []byte
41 // unescaped is where an escaped string too long for the arena is decoded to before it is copied, which is kept
42 // from a call to the next up to maxUnescapeScratchSize ( see unescapeLong ).
43 unescaped []byte
44 // value is a zero value of the type valueType in the heap, which UnmarshalOf decodes into
45 // before it copies the result to the value of the caller.
46 valueType unsafe.Pointer
47 value unsafe.Pointer
48 // recentDecoders are the decoders of the types decoded last, in the sets indexed by the address of the type.
49 // Only the contexts of the pool have them: a Decoder has a context of its own, which it would allocate
50 // with them for every stream.
51 recentDecoders *[recentDecoderSets]recentDecoderSet
52 // typeError is the first type error of the decoding, which is returned at its end ( see TypeError ). It is nil
53 // in a context of the pool: TypeError clears it, and DiscardTypeError when the decoding fails.
54 typeError *pendingTypeError
55 }
56
57 const (
58 // recentDecoderSets is the number of the sets of the recent decoders, of recentDecoderWays entries each,
59 // as the recent opcodes of the encoder: the set of a type is the top bits of the product of its address
60 // with an odd constant, and a set holds the two types hashed to it which were decoded last, so that the
61 // type passed to Unmarshal and a type held by its values of interface{} never evict each other.
62 recentDecoderSets = 16
63 recentDecoderHashShift = 64 - 4
64 recentDecoderWays = 2
65 )
66
67 type recentDecoder struct {
68 typeptr uintptr
69 dec Decoder
70 }
71
72 // recentDecoderSet is the entries of a set, the one decoded last first.
73 type recentDecoderSet [recentDecoderWays]recentDecoder
74
75 // DecoderOf returns the decoder of the type, compiling it if the type is new.
76 //
77 // A runtime context remembers the decoders of the types it decoded last: the same types are decoded again
78 // and again in most of the programs, and this is cheaper than a lookup of the table shared by every goroutine.
79 // The first entry of the set is looked at here, which is inlined into the callers; the rest in lookupDecoder.
80 func (ctx *RuntimeContext) DecoderOf(typ unsafe.Pointer) (Decoder, error) {
81 if ctx.recentDecoders == nil {
82 return CompileToGetDecoder(typ)
83 }
84 set := &ctx.recentDecoders[(uint64(uintptr(typ))*runtime.TypeHashMultiplier)>>recentDecoderHashShift]
85 if set[0].typeptr == uintptr(typ) {
86 return set[0].dec, nil
87 }
88 return lookupDecoder(set, typ)
89 }
90
91 // lookupDecoder returns the decoder of the type from the second entry of its set, or from the shared table,
92 // compiling it if the type is new. A decoder found in the shared table takes the first entry of the set,
93 // and the one decoded before it is kept in the second.
94 func lookupDecoder(set *recentDecoderSet, typ unsafe.Pointer) (Decoder, error) {
95 if set[1].typeptr == uintptr(typ) {
96 return set[1].dec, nil
97 }
98 dec, err := CompileToGetDecoder(typ)
99 if err != nil {
100 return nil, err
101 }
102 set[1] = set[0]
103 set[0] = recentDecoder{typeptr: uintptr(typ), dec: dec}
104 return dec, nil
105 }
106
107 const (
108 // minArenaChunkSize and arenaChunkSize are the sizes of the first and of the largest chunks of the arena
109 // of the strings: a chunk is twice as large as the previous one, so that a context which decodes a few
110 // short strings, as the one of a Decoder made for a small value, allocates little.
111 minArenaChunkSize = 64
112 arenaChunkSize = 16384
113 // maxArenaStringSize is the length of the longest string which is copied to the arena:
114 // a longer one gets an allocation of its own, which it alone keeps alive.
115 maxArenaStringSize = 512
116 // maxUnescapeScratchSize is the length of the longest escaped string which is decoded into the scratch bytes of
117 // a context: a longer one is decoded into bytes of its own, which the context doesn't keep.
118 maxUnescapeScratchSize = 64 << 10
119 )
120
121 // inputPadding is the number of the bytes the buffer of the input has after its nul byte, which the decoders
122 // may read: the words of an object key are read from any byte of the buffer ( see structDecoder.Decode ).
123 const inputPadding = 16
124
125 // SetInput copies data to the buffer of the context, followed by a nul byte which ends every scan,
126 // and makes it the buffer to decode.
127 func (ctx *RuntimeContext) SetInput(data []byte) []byte {
128 n := len(data) + 1
129 if cap(ctx.input) < n+inputPadding {
130 // at least a cache line, which the buffer of another context doesn't share: it is written for every call.
131 ctx.input = make([]byte, n, max(n+inputPadding, cacheLineSize))
132 }
133 buf := ctx.input[:n]
134 copy(buf, data)
135 buf[len(data)] = nul
136 ctx.Buf = buf
137 ctx.origin = data
138 return buf
139 }
140
141 // makeString returns the string of lit, which the string decoder returned from Buf: lit is either a part of Buf,
142 // which is reused by the next call and has the bytes of the input ( Buf is never written ), or a new slice of its
143 // own ( an escape was decoded, or an invalid UTF-8 sequence was replaced ).
144 //
145 // Only the buffer of Unmarshal is reused ( origin is its input ): the strings are copied out of it, or refer to
146 // the input under NoCopyStringOption. The other buffers, as the one of a stream, are never written again after
147 // a value is decoded, so the strings refer to them.
148 func (ctx *RuntimeContext) makeString(lit []byte) string {
149 if len(lit) == 0 {
150 return ""
151 }
152 if ctx.origin == nil {
153 return unsafe.String(unsafe.SliceData(lit), len(lit))
154 }
155 if (ctx.Option.Flags & NoCopyStringOption) != 0 {
156 return ctx.referString(lit)
157 }
158 return ctx.copyString(lit)
159 }
160
161 // isPartOf reports whether b is a part of buf.
162 func isPartOf(b, buf []byte) bool {
163 base := uintptr(unsafe.Pointer(unsafe.SliceData(buf)))
164 p := uintptr(unsafe.Pointer(unsafe.SliceData(b)))
165 return base <= p && p < base+uintptr(len(buf))
166 }
167
168 // referString returns a string which refers to the input, where lit is a part of Buf, without a copy.
169 func (ctx *RuntimeContext) referString(lit []byte) string {
170 if !isPartOf(lit, ctx.Buf) {
171 // a slice of its own
172 return unsafe.String(unsafe.SliceData(lit), len(lit))
173 }
174 off := uintptr(unsafe.Pointer(unsafe.SliceData(lit))) - uintptr(unsafe.Pointer(unsafe.SliceData(ctx.Buf)))
175 return unsafe.String(&ctx.origin[off], len(lit))
176 }
177
178 // reserveArena returns n bytes of the arena after its end, which a string may be written to:
179 // the caller extends the arena by the length of the string it wrote.
180 func (ctx *RuntimeContext) reserveArena(n int) []byte {
181 if cap(ctx.arena)-len(ctx.arena) < n {
182 size := min(max(2*cap(ctx.arena), minArenaChunkSize), arenaChunkSize)
183 ctx.arena = make([]byte, 0, max(size, n))
184 }
185 return ctx.arena[len(ctx.arena) : len(ctx.arena)+n]
186 }
187
188 // copyString returns a copy of lit, in the arena unless it is long.
189 func (ctx *RuntimeContext) copyString(lit []byte) string {
190 if len(lit) > maxArenaStringSize {
191 return string(lit)
192 }
193 dst := ctx.reserveArena(len(lit))
194 copy(dst, lit)
195 ctx.arena = ctx.arena[:len(ctx.arena)+len(lit)]
196 return unsafe.String(unsafe.SliceData(dst), len(lit))
197 }
198
199 // boxSlabSize is the number of the values a slab of floats or strings holds.
200 const boxSlabSize = 32
201
202 var (
203 float64TypePtr = runtime.TypePtr(reflect.TypeOf(float64(0)))
204 stringTypePtr = runtime.TypePtr(reflect.TypeOf(""))
205 )
206
207 // boxFloat returns f as an interface value, which refers to a slot of the slab of floats.
208 func (ctx *RuntimeContext) boxFloat(f float64) any {
209 if len(ctx.floats) == cap(ctx.floats) {
210 ctx.floats = make([]float64, 0, boxSlabSize)
211 }
212 ctx.floats = append(ctx.floats, f)
213 return *(*any)(unsafe.Pointer(&emptyInterface{typ: float64TypePtr, ptr: unsafe.Pointer(&ctx.floats[len(ctx.floats)-1])}))
214 }
215
216 // boxString returns s as an interface value, which refers to a slot of the slab of strings.
217 func (ctx *RuntimeContext) boxString(s string) any {
218 if len(ctx.strings) == cap(ctx.strings) {
219 ctx.strings = make([]string, 0, boxSlabSize)
220 }
221 ctx.strings = append(ctx.strings, s)
222 return *(*any)(unsafe.Pointer(&emptyInterface{typ: stringTypePtr, ptr: unsafe.Pointer(&ctx.strings[len(ctx.strings)-1])}))
223 }
224
225 // popAny removes the elements of anyStack from base, clearing them so that the stack keeps nothing alive.
226 func (ctx *RuntimeContext) popAny(base int) {
227 clear(ctx.anyStack[base:])
228 ctx.anyStack = ctx.anyStack[:base]
229 }
230
231 // anyEntry is an entry of an object being decoded into a map[string]interface{}.
232 type anyEntry struct {
233 key string
234 value any
235 }
236
237 // popEntries removes the entries of entryStack from base, clearing them so that the stack keeps nothing alive.
238 func (ctx *RuntimeContext) popEntries(base int) {
239 clear(ctx.entryStack[base:])
240 ctx.entryStack = ctx.entryStack[:base]
241 }
242
243 // cacheLineSize is the size of the cache lines the contexts are kept apart by: 128 bytes, which is the line of
244 // the Apple M processors and two lines of amd64, whose adjacent lines are fetched together.
245 const cacheLineSize = 128
246
247 // pooledContext is a context of the pool with its option, in one allocation which fills its cache lines: the
248 // contexts of the goroutines which decode at the same time are written for every call, so a context which
249 // shared a cache line with another made each goroutine wait for the other.
250 type pooledContext struct {
251 ctx RuntimeContext
252 opt Option
253 _ [cacheLineSize - (unsafe.Sizeof(RuntimeContext{})+unsafe.Sizeof(Option{}))%cacheLineSize]byte
254 }
255
256 var (
257 runtimeContextPool = sync.Pool{
258 New: func() any {
259 c := &pooledContext{}
260 c.ctx.Option = &c.opt
261 c.ctx.recentDecoders = &[recentDecoderSets]recentDecoderSet{}
262 return &c.ctx
263 },
264 }
265 )
266
267 func TakeRuntimeContext() *RuntimeContext {
268 return runtimeContextPool.Get().(*RuntimeContext)
269 }
270
271 func ReleaseRuntimeContext(ctx *RuntimeContext) {
272 // Nothing of the call is kept: the input of the caller may be referred to by the decoded strings.
273 ctx.Buf = nil
274 ctx.origin = nil
275 ctx.slot = nil
276 ctx.popAny(0)
277 ctx.popEntries(0)
278 // The strings refer to the input: the slab is not kept, so that a context in the pool doesn't keep
279 // the input of a previous call alive. The slab of floats refers to nothing and is kept.
280 ctx.strings = nil
281 runtimeContextPool.Put(ctx)
282 }
283
284 var (
285 isWhiteSpace = [256]bool{}
286 )
287
288 func init() {
289 isWhiteSpace[' '] = true
290 isWhiteSpace['\n'] = true
291 isWhiteSpace['\t'] = true
292 isWhiteSpace['\r'] = true
293 }
294
295 func char(ptr unsafe.Pointer, offset int64) byte {
296 return *(*byte)(unsafe.Add(ptr, offset))
297 }
298
299 func skipWhiteSpace(buf []byte, cursor int64) int64 {
300 for isWhiteSpace[buf[cursor]] {
301 cursor++
302 }
303 return cursor
304 }
305
306 // skipStringDecoder scans the strings which skipValue skips.
307 var skipStringDecoder = newStringDecoder("", "")
308
309 // skipString returns the position after the string at cursor. A string without an escape is skipped word by
310 // word up to its quote, where the buffer has room for the words ( the nul byte at its end stops them ), and, where the CPU has a SIMD scan, for its
311 // first 64 bytes, after which the rest of a long string is scanned by SIMD ( see scanStringRest ). Any other
312 // string is scanned as a string is decoded, and validated so. It is a function of its own, so that the code of
313 // skipValue for the other values is the same whatever a string takes.
314 func skipString(buf []byte, cursor int64) (int64, error) {
315 start := cursor + 1
316 wordsEnd := int64(len(buf))
317 if hasStringSIMD {
318 wordsEnd = min(wordsEnd, start+64)
319 }
320 c := start
321 for ; c+8 <= wordsEnd; c += 8 {
322 if special := keyEndBytes(load64(buf, c)); special != 0 {
323 c += int64(bits.TrailingZeros64(special) / 8)
324 if buf[c] == '"' {
325 return c + 1, nil
326 }
327 // an escape or a byte which is not valid in a string
328 return skipStringByScan(buf, cursor)
329 }
330 }
331 if c+8 > int64(len(buf)) {
332 // the end of the buffer, whose last bytes are scanned as a string
333 return skipStringByScan(buf, cursor)
334 }
335 _, next, _, err := skipStringDecoder.scanStringRest(buf, buf[start:c], c, stringInfo{firstEscape: -1})
336 if err != nil {
337 return 0, err
338 }
339 return next, nil
340 }
341
342 // skipStringByScan is skipString for any string, which it scans as a string is decoded.
343 func skipStringByScan(buf []byte, cursor int64) (int64, error) {
344 literal, next, info, err := skipStringDecoder.scanString(buf, cursor)
345 if next < 0 {
346 _, next, _, err = skipStringDecoder.scanStringRest(buf, literal, -next-1, info)
347 }
348 if err != nil {
349 return 0, err
350 }
351 return next, nil
352 }
353
354 func skipValue(buf []byte, cursor, depth int64) (int64, error) {
355 for {
356 switch buf[cursor] {
357 case ' ', '\t', '\n', '\r':
358 cursor++
359 continue
360 case '{', '[':
361 // the grammar of the object or the array, by skipFast without the call of skipGrammarFast
362 end, level, objects, resume, ev := skipFast(buf, cursor, 0, 0, resumeValue, skipMaxLevel(depth))
363 if ev == skipDone {
364 return end, nil
365 }
366 return skipGrammarEvent(buf, end, depth, level, objects, resume, ev)
367 case '"':
368 end, err := skipString(buf, cursor)
369 if err != nil {
370 return 0, stringError(buf, cursor, err)
371 }
372 return end, nil
373 case '1', '2', '3', '4', '5', '6', '7', '8', '9':
374 // an integer, which most numbers are, without a call
375 start := cursor
376 cursor++
377 for buf[cursor]-'0' <= 9 {
378 cursor++
379 }
380 if c := buf[cursor]; c == '.' || c == 'e' || c == 'E' {
381 return skipNumberRest(buf, start, cursor)
382 }
383 return cursor, nil
384 case '-', '0':
385 return skipNumber(buf, cursor)
386 case 't':
387 if buf[cursor+1] != 'r' || buf[cursor+2] != 'u' || buf[cursor+3] != 'e' {
388 return 0, literalSyntaxError(buf, cursor, "true")
389 }
390 return cursor + 4, nil
391 case 'f':
392 if buf[cursor+1] != 'a' || buf[cursor+2] != 'l' || buf[cursor+3] != 's' || buf[cursor+4] != 'e' {
393 return 0, literalSyntaxError(buf, cursor, "false")
394 }
395 return cursor + 5, nil
396 case 'n':
397 if buf[cursor+1] != 'u' || buf[cursor+2] != 'l' || buf[cursor+3] != 'l' {
398 return 0, literalSyntaxError(buf, cursor, "null")
399 }
400 return cursor + 4, nil
401 default:
402 return 0, syntaxErrorAt(buf, cursor, whereValue)
403 }
404 }
405 }
406
407 func validateTrue(buf []byte, cursor int64) error {
408 if cursor+3 >= int64(len(buf)) {
409 return errors.ErrUnexpectedEndOfJSON("true", cursor)
410 }
411 if buf[cursor+1] != 'r' {
412 return errors.ErrInvalidCharacter(buf[cursor+1], "true", cursor+1)
413 }
414 if buf[cursor+2] != 'u' {
415 return errors.ErrInvalidCharacter(buf[cursor+2], "true", cursor+2)
416 }
417 if buf[cursor+3] != 'e' {
418 return errors.ErrInvalidCharacter(buf[cursor+3], "true", cursor+3)
419 }
420 return nil
421 }
422
423 func validateFalse(buf []byte, cursor int64) error {
424 if cursor+4 >= int64(len(buf)) {
425 return errors.ErrUnexpectedEndOfJSON("false", cursor)
426 }
427 if buf[cursor+1] != 'a' {
428 return errors.ErrInvalidCharacter(buf[cursor+1], "false", cursor+1)
429 }
430 if buf[cursor+2] != 'l' {
431 return errors.ErrInvalidCharacter(buf[cursor+2], "false", cursor+2)
432 }
433 if buf[cursor+3] != 's' {
434 return errors.ErrInvalidCharacter(buf[cursor+3], "false", cursor+3)
435 }
436 if buf[cursor+4] != 'e' {
437 return errors.ErrInvalidCharacter(buf[cursor+4], "false", cursor+4)
438 }
439 return nil
440 }
441
442 func validateNull(buf []byte, cursor int64) error {
443 if cursor+3 >= int64(len(buf)) {
444 return errors.ErrUnexpectedEndOfJSON("null", cursor)
445 }
446 if buf[cursor+1] != 'u' {
447 return errors.ErrInvalidCharacter(buf[cursor+1], "null", cursor+1)
448 }
449 if buf[cursor+2] != 'l' {
450 return errors.ErrInvalidCharacter(buf[cursor+2], "null", cursor+2)
451 }
452 if buf[cursor+3] != 'l' {
453 return errors.ErrInvalidCharacter(buf[cursor+3], "null", cursor+3)
454 }
455 return nil
456 }
457
458 // valuePools are the zero values of every type which UnmarshalOf decoded, besides the one a context keeps.
459 var valuePools runtime.TypeCache[sync.Pool]
460
461 // TakeValue returns the address of a zero value of typ in the heap, which the context keeps for the next call
462 // with the same type. typ is given as its type descriptor too, which is how it is looked up.
463 func (ctx *RuntimeContext) TakeValue(typ reflect.Type, typeptr unsafe.Pointer) unsafe.Pointer {
464 if ctx.valueType == typeptr {
465 return ctx.value
466 }
467 if ctx.valueType != nil {
468 valuePool(ctx.valueType).Put(ctx.value)
469 }
470 ctx.valueType = typeptr
471 if v := valuePool(typeptr).Get(); v != nil {
472 ctx.value = v.(unsafe.Pointer)
473 } else {
474 ctx.value = newValue(typ)
475 }
476 return ctx.value
477 }
478
479 func valuePool(typeptr unsafe.Pointer) *sync.Pool {
480 if pool := valuePools.Load(uintptr(typeptr)); pool != nil {
481 return pool
482 }
483 return valuePools.Store(uintptr(typeptr), &sync.Pool{})
484 }