Debian Codegraph @

internal/decoder/stream.go

raw
1 package decoder
2
3 import (
4 "bytes"
5 "io"
6 "math/bits"
7 "unsafe"
8
9 "github.com/goccy/go-json/internal/errors"
10 "github.com/goccy/go-json/internal/runtime"
11 )
12
13 const (
14 // initBufSize is the size of the buffer of a new stream.
15 initBufSize = 512
16 // bufPadding is the number of the bytes kept free after the data in the buffer of a stream:
17 // one for the nul byte which ends the value being decoded, the rest so that a scan reads
18 // a whole block from any byte of the value.
19 bufPadding = scanBlockSize
20 )
21
22 // Stream reads the values of a JSON text from an io.Reader one by one.
23 //
24 // A value is decoded by the same decoders as a byte slice is: the stream reads until its buffer
25 // holds the whole value ( scanValue ), puts a nul byte after the value and lets the decoder work
26 // on the buffer. The decoded strings refer to the buffer, so a byte which has been read is never
27 // overwritten: when the buffer is full, the bytes which are not consumed yet are copied to a new one.
28 type Stream struct {
29 // buf[:length] is what has been read, buf[length] is nul, and bufPadding bytes are free at the end.
30 buf []byte
31 length int64
32 // cursor is the first byte which is not consumed yet.
33 cursor int64
34 // offset is the number of the bytes discarded before buf[0]: the total offset is offset + cursor.
35 offset int64
36 r io.Reader
37 // readErr is the error the reader returned. Once set, the reader is never read again:
38 // the data read before the error is consumed first, then the error is reported.
39 readErr error
40 ctx *RuntimeContext
41 Option *Option
42 // prevEnd is the total offset of the end of the previous value, which the offset of a type error may be
43 // relative to ( see StreamOffsetBase ).
44 prevEnd int64
45 // tokenState is where the stream is between the tokens, and tokenStack the states of the objects and the
46 // arrays which Token opened, the innermost last ( see Token ).
47 tokenState tokenState
48 tokenStack []tokenState
49 // err is the error which a read failed with, which every read returns after it, as encoding/json does, and
50 // errOffset the total offset which InputOffset reports after it: the end of the previous value.
51 err error
52 errOffset int64
53 // readStart is the total offset where the read of the value of Decode, or of the value of Token, started, and
54 // scanned the number of the bytes which these reads read before it, by which encoding/json before Go 1.27
55 // reports the offset of a syntax error of the value ( see scannedOffset ).
56 readStart int64
57 scanned int64
58 // more is what More peeked at, which InputOffset reports ( see streamPeek ).
59 more streamPeek
60 // keeps is set while the bytes from the total offset keepFrom are kept in the buffer, before the cursor too:
61 // a read of a token which fails leaves the stream where it was ( see Token ).
62 keeps bool
63 keepFrom int64
64 }
65
66 func NewStream(r io.Reader) *Stream {
67 opt := &Option{}
68 return &Stream{
69 r: r,
70 buf: make([]byte, initBufSize+bufPadding),
71 ctx: &RuntimeContext{Option: opt},
72 Option: opt,
73 }
74 }
75
76 // markPrevEnd keeps the end of the previous value of the stream: the offsets of the type errors of the next value
77 // may be relative to it ( see StreamOffsetBase ), and InputOffset reports it after a read which fails.
78 func (s *Stream) markPrevEnd() {
79 s.prevEnd = s.offset + s.cursor
80 }
81
82 // fail keeps err, the error which a read failed with, which every read returns after it, as encoding/json does.
83 //
84 //go:noinline
85 func (s *Stream) fail(err error) error {
86 s.err, s.errOffset, s.tokenState = err, s.prevEnd, tokenFailed
87 return err
88 }
89
90 // TotalOffset returns the number of the bytes consumed from the reader.
91 func (s *Stream) TotalOffset() int64 {
92 return s.offset + s.cursor
93 }
94
95 // Buffered returns a reader of the data read from the reader but not consumed yet.
96 func (s *Stream) Buffered() io.Reader {
97 return bytes.NewReader(s.buf[s.cursor:s.length])
98 }
99
100 // read reads more bytes from the reader into the buffer.
101 // It returns false when nothing more can be read: the reader ended or failed ( readErr ).
102 func (s *Stream) read() bool {
103 if s.readErr != nil {
104 return false
105 }
106 if int64(len(s.buf))-s.length <= bufPadding {
107 s.grow()
108 }
109 n, err := s.r.Read(s.buf[s.length : int64(len(s.buf))-bufPadding])
110 s.length += int64(n)
111 s.buf[s.length] = nul
112 if err != nil {
113 s.readErr = err
114 }
115 return n > 0 || err == nil
116 }
117
118 // grow moves the bytes which are not consumed yet to a new buffer, so that the reader
119 // has room to read into. The old buffer is left to the strings which refer to it.
120 func (s *Stream) grow() {
121 // the bytes from the cursor are moved, or from the one which is kept before it
122 from := s.cursor
123 if keep := s.keepFrom - s.offset; s.keeps && keep >= 0 && keep < from {
124 from = keep
125 }
126 remain := s.length - from
127 size := int64(len(s.buf)) - bufPadding
128 if remain*2 > size {
129 // The data which is not consumed yet fills more than half of the buffer: it is a value
130 // larger than the buffer, which is grown faster so that it is copied fewer times.
131 size *= 4
132 }
133 if r, ok := s.r.(interface{ Len() int }); ok {
134 // The reader knows how much is left ( bytes.Reader, strings.Reader, bytes.Buffer ):
135 // the buffer holds all of it at once, so that nothing is copied again.
136 size = remain + int64(r.Len())
137 }
138 buf := make([]byte, size+bufPadding)
139 copy(buf, s.buf[from:s.length])
140 s.offset += from
141 s.buf = buf
142 s.length = remain
143 s.cursor -= from
144 }
145
146 // fill makes sure that the buffer holds the byte at the cursor.
147 func (s *Stream) fill() bool {
148 for s.cursor >= s.length {
149 if !s.read() {
150 return false
151 }
152 }
153 return true
154 }
155
156 // endError is the error reported when the reader has nothing more: io.EOF or what the reader returned.
157 func (s *Stream) endError() error {
158 if s.readErr != nil {
159 return s.readErr
160 }
161 return io.EOF
162 }
163
164 // truncatedValueError is the error reported when the reader ends in the middle of the value at the cursor: the first
165 // syntax error of what has been read, as encoding/json reads a value byte by byte, or the unexpected end.
166 //
167 //go:noinline
168 func (s *Stream) truncatedValueError() error {
169 if err := s.valueSyntaxError(); err != nil {
170 return err
171 }
172 return s.unexpectedEndError()
173 }
174
175 // unexpectedEndError is the error reported when the reader ends in the middle of a value.
176 func (s *Stream) unexpectedEndError() error {
177 if s.readErr != nil && s.readErr != io.EOF {
178 return s.readErr
179 }
180 return io.ErrUnexpectedEOF
181 }
182
183 // skipWhiteSpace moves the cursor to the next byte which is not white space.
184 // It returns false when the reader has nothing more.
185 func (s *Stream) skipWhiteSpace() bool {
186 for {
187 if !s.fill() {
188 return false
189 }
190 switch s.buf[s.cursor] {
191 case ' ', '\n', '\t', '\r':
192 s.cursor++
193 default:
194 return true
195 }
196 }
197 }
198
199 // peek moves the cursor to the next byte which is not a white space, as skipWhiteSpace does, but leaves it where it
200 // is when the input ends with white spaces only: the offset of the input doesn't count them, as encoding/json
201 // doesn't count what it peeks at. It returns false when the reader has nothing more.
202 func (s *Stream) peek() bool {
203 var rel int64
204 for {
205 // the position is kept relative to the cursor, because a read may move the data ( grow )
206 for pos := s.cursor + rel; pos < s.length; pos++ {
207 if !isWhiteSpace[s.buf[pos]] {
208 s.cursor = pos
209 return true
210 }
211 }
212 rel = s.length - s.cursor
213 if !s.read() {
214 return false
215 }
216 }
217 }
218
219 // prepare moves the cursor to the beginning of the next value: the white space is skipped, and, between the
220 // tokens of an object or an array, the comma or the colon which the grammar has before the value.
221 func (s *Stream) prepare() error {
222 if s.tokenState != tokenTopValue {
223 return s.prepareInTokens()
224 }
225 s.readStart = s.offset + s.cursor
226 if !s.skipWhiteSpace() {
227 return s.fail(s.endError())
228 }
229 return nil
230 }
231
232 // isLiteralChar is true for the bytes of a number, true, false and null.
233 var isLiteralChar = [256]bool{
234 '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,
235 '-': true, '+': true, '.': true, 'e': true, 'E': true,
236 't': true, 'r': true, 'u': true, 'f': true, 'a': true, 'l': true, 's': true, 'n': true,
237 }
238
239 // scanValue finds the end of the value which begins at the cursor, reading from the reader as needed,
240 // and returns the position after the value. The value is not validated: the decoder does it.
241 // The cursor is not moved: the value is in buf[cursor:end], but the buffer may have been replaced.
242 func (s *Stream) scanValue() (int64, error) {
243 if !s.fill() {
244 return 0, s.endError()
245 }
246 switch c := s.buf[s.cursor]; {
247 case c == '{' || c == '[':
248 return s.scanCompound()
249 case c == '"':
250 return s.scanString()
251 case isLiteralChar[c]:
252 return s.scanLiteral()
253 }
254 // The decoder reports the invalid character.
255 return s.cursor + 1, nil
256 }
257
258 // scanCompound finds the end of the object or the array at the cursor: the position after the bracket
259 // which closes it.
260 func (s *Stream) scanCompound() (int64, error) {
261 // The position is kept relative to the cursor, because a read may move the data ( grow ).
262 var rel int64
263 sc := compoundScanner{maxDepth: maxDecodeNestingDepth}
264 for {
265 pos, found, err := sc.scan(s.buf, s.cursor+rel, s.length)
266 if err != nil {
267 return 0, s.totalOffsetError(err)
268 }
269 if found {
270 return pos, nil
271 }
272 rel = pos - s.cursor
273 if !s.read() {
274 return 0, s.truncatedValueError()
275 }
276 }
277 }
278
279 // scanString finds the end of the string at the cursor: the position after the quote which closes it.
280 func (s *Stream) scanString() (int64, error) {
281 var (
282 rel int64 = 1 // after the opening quote
283 escaped bool
284 )
285 for {
286 buf := s.buf
287 pos := s.cursor + rel
288 end := s.length
289 for pos+8 <= end {
290 w := load64(buf, pos)
291 if byteMask(w, '\\') != 0 || escaped {
292 break
293 }
294 if quote := byteMask(w, '"'); quote != 0 {
295 return pos + int64(bits.TrailingZeros64(quote)/8) + 1, nil
296 }
297 pos += 8
298 }
299 lim := min(pos+8, end)
300 for pos < lim {
301 c := buf[pos]
302 pos++
303 switch {
304 case escaped:
305 escaped = false
306 case c == '\\':
307 escaped = true
308 case c == '"':
309 return pos, nil
310 }
311 }
312 rel = pos - s.cursor
313 if pos < end {
314 continue
315 }
316 if !s.read() {
317 return 0, s.truncatedValueError()
318 }
319 }
320 }
321
322 // scanLiteral finds the end of the number, true, false or null at the cursor: the position of
323 // the first byte which can't belong to it, or the end of the input. The bytes may be more than one value, as 01 is
324 // 0 and 1, which the decoder rejects: Decode then decodes the first alone ( see decodeError ).
325 func (s *Stream) scanLiteral() (int64, error) {
326 var rel int64
327 for {
328 buf := s.buf
329 pos := s.cursor + rel
330 end := s.length
331 for pos < end {
332 if !isLiteralChar[buf[pos]] {
333 return pos, nil
334 }
335 pos++
336 }
337 rel = pos - s.cursor
338 if !s.read() {
339 if s.readErr != io.EOF {
340 return 0, s.readErr
341 }
342 return s.cursor + rel, nil
343 }
344 }
345 }
346
347 // streamNumberEnd returns the end of the number at start in buf[:lim] by the grammar of the numbers, which may be
348 // cut there: what follows is not read yet, or is the next value.
349 func streamNumberEnd(buf []byte, start, lim int64) int64 {
350 isDigit := func(i int64) bool { return i < lim && buf[i]-'0' <= 9 }
351 i := start
352 if buf[i] == '-' {
353 i++
354 }
355 if i < lim && buf[i] == '0' {
356 i++
357 } else {
358 for isDigit(i) {
359 i++
360 }
361 }
362 if i < lim && buf[i] == '.' {
363 for i++; isDigit(i); i++ {
364 }
365 }
366 if i < lim && (buf[i] == 'e' || buf[i] == 'E') {
367 i++
368 if i < lim && (buf[i] == '+' || buf[i] == '-') {
369 i++
370 }
371 for isDigit(i) {
372 i++
373 }
374 }
375 return i
376 }
377
378 // DecoderOf returns the decoder of the type, from the recent decoders of the context of the stream.
379 func (s *Stream) DecoderOf(typ unsafe.Pointer) (Decoder, error) {
380 return s.ctx.DecoderOf(typ)
381 }
382
383 // Decode decodes the next value of the stream into p, of the pointer type typ, by dec. If the value has a type
384 // error, the stream goes on after the value, as the one of encoding/json does.
385 func (s *Stream) Decode(dec Decoder, typ unsafe.Pointer, p unsafe.Pointer) error {
386 s.markPrevEnd()
387 if err := s.prepare(); err != nil {
388 return err
389 }
390 end, err := s.scanValue()
391 if err != nil {
392 return s.fail(err)
393 }
394 ctx := s.ctx
395 ctx.Option = s.Option
396 var cursor int64
397 if c := s.buf[s.cursor]; c != 't' && c != 'f' && c != 'n' {
398 // The end of the value is known exactly: a nul byte is put there while the value is decoded,
399 // so that the decoder never reads the next value, whatever it makes of a malformed one.
400 // A number needs it too, because the decoder validates the byte which ends it.
401 saved := s.buf[end]
402 s.buf[end] = nul
403 ctx.Buf = s.buf[:end+1]
404 cursor, err = dec.Decode(ctx, s.cursor, 0, p)
405 s.buf[end] = saved
406 } else {
407 // true, false and null end at the first byte which can't belong to them, and the decoder
408 // reports that byte when it is wrong: it sees the whole buffer, ended by the nul byte.
409 ctx.Buf = s.buf[:s.length+1]
410 cursor, err = dec.Decode(ctx, s.cursor, 0, p)
411 }
412 ctx.Buf = nil
413 if err != nil {
414 return s.decodeError(err, dec, typ, p, end)
415 }
416 if ctx.HasTypeError() {
417 return s.typeError(typ, cursor)
418 }
419 s.cursor = cursor
420 if countsScanned {
421 s.scanned += s.offset + cursor - s.readStart
422 }
423 s.more.reset()
424 if s.tokenState != tokenTopValue {
425 s.tokenValueEnd()
426 }
427 return nil
428 }
429
430 // decodeError returns the error of the decoder, whose offset is made the one in the whole input, of the value at
431 // the cursor, which scanValue ended at end. A type error before it is not kept for the next value.
432 //
433 // A syntax error is the first one of the value by the grammar, as encoding/json reports it: it checks the value
434 // before it decodes it. The decoder never writes the buffer, which keeps the input.
435 //
436 //go:noinline
437 func (s *Stream) decodeError(err error, dec Decoder, typ, p unsafe.Pointer, end int64) error {
438 if c := s.buf[s.cursor]; c == '-' || c-'0' <= 9 {
439 if first := streamNumberEnd(s.buf, s.cursor, end); first < end {
440 // the bytes of the numbers which scanLiteral read are more than one value, as 01 is 0 and 1: the first
441 // is decoded alone, and the next one after it
442 s.ctx.DiscardTypeError()
443 return s.decodeFirstNumber(dec, typ, p, first)
444 }
445 }
446 s.ctx.DiscardTypeError()
447 if _, ok := err.(*errors.SyntaxError); ok {
448 if serr := s.valueSyntaxError(); serr != nil {
449 return s.fail(serr)
450 }
451 }
452 return s.fail(s.totalOffsetError(err))
453 }
454
455 // decodeFirstNumber decodes the number at the cursor, which ends at end by the grammar, as Decode does.
456 func (s *Stream) decodeFirstNumber(dec Decoder, typ, p unsafe.Pointer, end int64) error {
457 ctx := s.ctx
458 saved := s.buf[end]
459 s.buf[end] = nul
460 ctx.Buf = s.buf[:end+1]
461 cursor, err := dec.Decode(ctx, s.cursor, 0, p)
462 s.buf[end] = saved
463 ctx.Buf = nil
464 if err != nil {
465 s.ctx.DiscardTypeError()
466 if serr := s.valueSyntaxError(); serr != nil {
467 return s.fail(serr)
468 }
469 return s.fail(s.totalOffsetError(err))
470 }
471 if ctx.HasTypeError() {
472 return s.typeError(typ, cursor)
473 }
474 s.cursor = cursor
475 if countsScanned {
476 s.scanned += s.offset + cursor - s.readStart
477 }
478 s.more.reset()
479 if s.tokenState != tokenTopValue {
480 s.tokenValueEnd()
481 }
482 return nil
483 }
484
485 // valueSyntaxError returns the first syntax error of the value at the cursor by the grammar, in what has been read:
486 // the error of a byte, with its offset in the whole input, or the unexpected end of the input, where encoding/json
487 // reads more. A number, true, false or null is followed by the byte after it, or by the end of the input: the scan
488 // of the value has read either. It is nil if what has been read has none.
489 //
490 //go:noinline
491 func (s *Stream) valueSyntaxError() error {
492 _, err := skipValue(s.buf[:s.length+1], s.cursor, 0)
493 if err == nil {
494 return nil
495 }
496 if errors.IsAtEnd(err) {
497 return s.unexpectedEndError()
498 }
499 if at, ok := errors.ValueStartAt(err); ok {
500 if merr := s.valueStartMismatch(at); merr != nil {
501 return merr
502 }
503 }
504 return s.scannedOffset(s.totalOffsetError(err))
505 }
506
507 // scannedOffset makes the offset of the syntax error of the value read from readStart the one which encoding/json
508 // of the Go version reports ( see countsScanned ).
509 func (s *Stream) scannedOffset(err error) error {
510 if e, ok := err.(*errors.SyntaxError); ok && countsScanned {
511 e.Offset += s.scanned - s.readStart
512 }
513 return err
514 }
515
516 // typeError returns the type error of the value of the pointer type typ which Decode decoded from the cursor up
517 // to end, and moves the cursor after the value: the stream goes on after it, as the one of encoding/json does.
518 // Its offset is relative to the value, as encoding/json of the Go version reports it ( see StreamOffsetBase ).
519 // It takes the decoder of the type again, so that Decode keeps nothing more across its call of the decoder.
520 //
521 //go:noinline
522 func (s *Stream) typeError(typ unsafe.Pointer, end int64) error {
523 start := s.cursor
524 s.cursor = end
525 if countsScanned {
526 s.scanned += s.offset + end - s.readStart
527 }
528 s.more.reset()
529 if s.tokenState != tokenTopValue {
530 s.tokenValueEnd()
531 }
532 ctx := s.ctx
533 dec, err := s.DecoderOf(typ)
534 if err != nil {
535 ctx.DiscardTypeError()
536 return err
537 }
538 // the path of the error is walked in the value ended by the nul byte, as it was decoded
539 saved := s.buf[end]
540 s.buf[end] = nul
541 ctx.Buf = s.buf[:end+1]
542 base := StreamOffsetBase(s.prevEnd, s.offset+start) - s.offset
543 err = ctx.TypeError(dec, runtime.TypeOfPtr(typ), start, base)
544 ctx.Buf = nil
545 s.buf[end] = saved
546 return err
547 }
548
549 // totalOffsetError makes the offset of an error of the decoder, which is relative to the buffer,
550 // the offset in the whole input.
551 func (s *Stream) totalOffsetError(err error) error {
552 switch e := err.(type) {
553 case *errors.SyntaxError:
554 e.Offset += s.offset
555 case *errors.UnmarshalTypeError:
556 e.Offset += s.offset
557 }
558 return err
559 }
560
561 // tokenString decodes the string at the cursor by the string decoder, as Decode does.
562 func (s *Stream) tokenString() (any, error) {
563 s.readStart = s.offset + s.cursor
564 end, err := s.scanValue()
565 if err != nil {
566 return nil, err
567 }
568 saved := s.buf[end]
569 s.buf[end] = nul
570 literal, _, err := tokenStringDecoder.decodeByte(s.buf[:end+1], s.cursor)
571 s.buf[end] = saved
572 if err != nil {
573 if serr := s.valueSyntaxError(); serr != nil {
574 return nil, serr
575 }
576 return nil, s.totalOffsetError(err)
577 }
578 s.cursor = end
579 if countsScanned {
580 s.scanned += s.offset + end - s.readStart
581 }
582 if len(literal) != 0 && !isPartOf(literal, s.buf) {
583 // the bytes of the escaped string, which decodeLiteral made: they are the string's own
584 return unsafe.String(unsafe.SliceData(literal), len(literal)), nil
585 }
586 return string(literal), nil
587 }
588
589 var tokenStringDecoder = newStringDecoder("", "")