Source File
stream.go
Belonging Package
github.com/goccy/go-json/internal/decoder
package decoderimport ()const (// initBufSize is the size of the buffer of a new stream, and the most bytes a read reads: the buffer grows only for// a token longer than it, or a value which is kept whole ( see grow ).initBufSize = 512// bufPadding is the number of the bytes kept free after the data in the buffer of a stream:// one for the nul byte which ends the value being decoded, the rest so that a scan reads// a whole block from any byte of the value.bufPadding = scanBlockSize)// Stream reads the values of a JSON text from an io.Reader one by one.//// A value is decoded by the same decoders as a byte slice is: a value which the buffer holds whole is decoded from// it, with a nul byte put after the value, and an object or an array which it doesn't is decoded element by element// as it is read ( see scanFailed ), so that the buffer keeps its size. The decoded strings are copied out of the// buffer, so that a value keeps alive no memory but its own, and the buffer is reused in place when it is full: the// bytes which are not consumed yet are moved to its start. Under NoCopyStringOption, the strings refer to the// buffer, which is then never written again: the bytes are copied to a new one instead ( see referred ).type Stream struct {// buf[:length] is what has been read, buf[length] is nul, and bufPadding bytes are free at the end.buf []bytelength int64// cursor is the first byte which is not consumed yet.cursor int64// offset is the number of the bytes discarded before buf[0]: the total offset is offset + cursor.offset int64r io.Reader// readErr is the error the reader returned. Once set, the reader is never read again:// the data read before the error is consumed first, then the error is reported.readErr errorctx *RuntimeContextOption *Option// prevEnd is the total offset of the end of the previous value, which InputOffset reports after a read which// fails.prevEnd int64// tokenState is where the stream is between the tokens, and tokenStack the states of the objects and the// arrays which Token opened, the innermost last ( see Token ).tokenState tokenStatetokenStack []tokenState// err is the error which a read failed with, which every read returns after it, as encoding/json does, and// errOffset the total offset which InputOffset reports after it: the end of the previous value.err errorerrOffset int64// readStart is the total offset where the read of the value of Decode, or of the value of Token, started, and// scanned the number of the bytes which these reads read before it, by which encoding/json before Go 1.27// reports the offset of a syntax error of the value ( see scannedOffset ).readStart int64scanned int64// more is what More peeked at, which InputOffset reports ( see streamPeek ).more streamPeek// keeps is set while the bytes from the total offset keepFrom are kept in the buffer, before the cursor too:// a read of a token which fails leaves the stream where it was ( see Token ).keeps boolkeepFrom int64// src is the jsontext.Decoder whose buffer the stream reads in place, for a decoding of v2 ( see BorrowV2 ):// a read reads more into that buffer, which is buf, and own is the buffer of the stream then.src unsafe.Pointerown []byte// elements is where the objects and the arrays of the value which is decoded element by element end, which the// lookups extend ( see indexAt ), made for the first such value and kept for the next ones, which allocate its// entries no more. It is nil until a value is decoded so.elements *bracketIndex// referred is whether a decoded value may refer to the buffer, which grow doesn't reuse in place then: the// decoded strings are copied out of it, unless NoCopyStringOption is set, under which a value refers to the// buffer it is decoded from ( see Stream.Decode and scanFailed ). It is about the buffer, not about the values:// a new buffer is referred to only by the value being decoded ( see grow ). The bytes given to UnmarshalText, of// a value or a map key, are a part of the buffer, which may be written again then: encoding.TextUnmarshaler has// the method copy them to keep them, and the Decoder of encoding/json gives a part of its buffer too.referred bool}// ReadAllV2 returns the whole input of the stream, which has read nothing yet, up to the end of its reader, followed// by a nul byte and the padding which the decoders may read after it ( see SetInput ), or the error of the reader if it// fails.func ( *Stream) () ([]byte, error) {, := io.ReadAll(.r)if != nil {return nil,}return append(slices.Grow(, 1+inputPadding), nul), nil}func ( io.Reader) *Stream {:= &Option{}return &Stream{r: ,buf: make([]byte, initBufSize+bufPadding),ctx: &RuntimeContext{Option: },Option: ,}}// markPrevEnd keeps the end of the previous value of the stream, which InputOffset reports after a read which fails.func ( *Stream) () {.prevEnd = .offset + .cursor}// fail keeps err, the error which a read failed with, which every read returns after it, as encoding/json does.////go:noinlinefunc ( *Stream) ( error) error {.err, .errOffset, .tokenState = , .prevEnd, tokenFailedreturn}// TotalOffset returns the number of the bytes consumed from the reader.func ( *Stream) () int64 {return .offset + .cursor}// Buffered returns a reader of the data read from the reader but not consumed yet.func ( *Stream) () io.Reader {return bytes.NewReader(.buf[.cursor:.length])}// read reads more bytes from the reader into the buffer, initBufSize bytes at most, whatever the size of the buffer.// It returns false when nothing more can be read: the reader ended or failed ( readErr ).func ( *Stream) () bool {if .readErr != nil {return false}if .src != nil {return .readSource()}if int64(len(.buf))-.length <= bufPadding {.grow()}, := .r.Read(.buf[.length:min(int64(len(.buf))-bufPadding, .length+initBufSize)]).length += int64().buf[.length] = nulif != nil {.readErr =}return > 0 || == nil}// grow moves the bytes which are not consumed yet to the start of a buffer, so that the reader has room to read into:// the same one, if nothing refers to it ( see referred ) and it has room for the bytes, or else a new one, as the// old buffer is left to the strings which refer to it.func ( *Stream) () {if := .ctx.v2; != nil && len(.pathNames) != 0 {// the names of the path which the levels have by their places in the buffer, which the bytes are moved from.copyNames()}:= .keepStart():= .length -:= int64(len(.buf)) - bufPaddingif >= {// What is not consumed yet fills the buffer: a token longer than it, or a value which is kept whole ( see// wholeEnd ). The buffer grows only for it, twice as large.*= 2}:= .bufif .referred || > int64(len())-bufPadding {= make([]byte, +bufPadding)// nothing refers to the new buffer yet, unless the value being decoded refers to it under NoCopyStringOption:// an option may clear the flag before the next value.referred = (.Option.Flags & NoCopyStringOption) != 0}copy(, .buf[:.length]).offset +=.buf =.length =.cursor -=}// keepStart returns the position of the first byte of the buffer which a read keeps: the cursor, or the first byte// which is kept before it, or the end of the token before the value which a skip of v2 reads, where an error is found// again from ( see skipLongV2 ).func ( *Stream) () int64 {:= .cursorif := .keepFrom - .offset; .keeps && >= 0 && < {=}if := .ctx.v2; != nil && .skip.active {= min(, .skipKeepFrom())}return}// fill makes sure that the buffer holds the byte at the cursor.func ( *Stream) () bool {for .cursor >= .length {if !.read() {return false}}return true}// endError is the error reported when the reader has nothing more: io.EOF or what the reader returned.func ( *Stream) () error {if .readErr != nil {return .readErr}return io.EOF}// truncatedValueError is the error reported when the reader ends in the middle of the value at the cursor: the first// syntax error of what has been read, as encoding/json reads a value byte by byte, or the unexpected end.////go:noinlinefunc ( *Stream) () error {if := .valueSyntaxError(); != nil {return}return .unexpectedEndError()}// unexpectedEndError is the error reported when the reader ends in the middle of a value.func ( *Stream) () error {if .readErr != nil && .readErr != io.EOF {return .readErr}return io.ErrUnexpectedEOF}// skipWhiteSpace moves the cursor to the next byte which is not white space.// It returns false when the reader has nothing more.func ( *Stream) () bool {// a byte which is not white space, as the tokens of most values are not separated by any, without a callif .cursor < .length && !isWhiteSpace[.buf[.cursor]] {return true}return .skipWhiteSpaceRest()}// skipWhiteSpaceRest is skipWhiteSpace without its check of the byte at the cursor first.func ( *Stream) () bool {for {// the nul byte at the end of what has been read stops the skipif .cursor = skipWhiteSpace(.buf, .cursor); .cursor < .length {return true}if !.read() {return false}}}// peek moves the cursor to the next byte which is not a white space, as skipWhiteSpace does, but leaves it where it// is when the input ends with white spaces only: the offset of the input doesn't count them, as encoding/json// doesn't count what it peeks at. It returns false when the reader has nothing more.func ( *Stream) () bool {var int64for {// the position is kept relative to the cursor, because a read may move the data ( grow )for := .cursor + ; < .length; ++ {if !isWhiteSpace[.buf[]] {.cursor =return true}}= .length - .cursorif !.read() {return false}}}// prepare moves the cursor to the beginning of the next value: the white space is skipped, and, between the// tokens of an object or an array, the comma or the colon which the grammar has before the value.func ( *Stream) () error {if .tokenState != tokenTopValue {return .prepareInTokens()}.readStart = .offset + .cursorif !.skipSpaceBefore() {return .fail(.endError())}return nil}// skipSpaceBefore is skipWhiteSpace for the white space before a value of the stream, which is little.func ( *Stream) () bool {for {if !.fill() {return false}switch .buf[.cursor] {case ' ', '\n', '\t', '\r':.cursor++default:return true}}}// isLiteralChar is true for the bytes of a number, true, false and null.var isLiteralChar = [256]bool{'0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,'-': true, '+': true, '.': true, 'e': true, 'E': true,'t': true, 'r': true, 'u': true, 'f': true, 'a': true, 'l': true, 's': true, 'n': true,}// scanValue finds the end of the value which begins at the cursor, reading from the reader as needed, and returns the// position after the value. The value is not validated: the decoder does it. The cursor is not moved: the value is in// buf[cursor:end], but the buffer may have been replaced. A string, a number, true, false and null are read whole; an// object or an array which doesn't end in what has been read is not read on: errLongValue is returned, and it is// decoded element by element ( see scanFailed ).func ( *Stream) () (int64, error) {if !.fill() {return 0, .endError()}switch := .buf[.cursor]; {case == '{' || == '[':return .scanCompound()case == '"':return .scanString()case isLiteralChar[]:return .scanLiteral()}// The decoder reports the invalid character.return .cursor + 1, nil}// scanCompound finds the end of the object or the array at the cursor in what has been read: the position after the// bracket which closes it, or errLongValue if it doesn't end there.func ( *Stream) () (int64, error) {var compoundScanner, := .scan(.buf, .cursor, .length)if ! {return 0, errLongValue}return , nil}// scanString finds the end of the string at the cursor: the position after the quote which closes it, or, for a string// which goes on past what has been read, after a control character or the byte of an escape which is not one, which a// string can't have: the decoder reports it, and the input after it is not read ( see scanStringInfo ).func ( *Stream) () (int64, error) {var (int64 = 1 // after the opening quotebool)for {:= .buf:= .cursor +:= .lengthfor +8 <= {:= load64(, )if byteMask(, '\\') != 0 || {break}if := byteMask(, '"'); != 0 {return + int64(bits.TrailingZeros64()/8) + 1, nil}+= 8}:= min(+8, )for < {:= []++switch {case := falsecase == '\\':= truecase == '"':return , nil}}= - .cursorif < {continue}// a string which goes on past what has been read is checked before a read, , , := .scanStringInfo()return ,}}// scanStringInfo is scanString which also returns what the string has, as stringDecoder.scanString does, and whether// it ends at its quote, and is valid then.func ( *Stream) () (int64, stringInfo, bool, error) {var (int64 = 1 // after the opening quotebool// hex is the number of the hexadecimal digits of a \u escape which are not read yetint// high has the high bits of the bytes, and firstEscape is the offset of the first backslash in the stringuint64int64 = -1)for {:= .buf:= .cursor +:= .length// the words of the bytes up to a quote, a backslash or a control character, which the nul byte at the end of// what has been read isif ! && == 0 {for := int64(len()); +8 <= ; += 8 {:= load64(, )if := keyEndBytes(); != 0 {// a quote, a backslash or a control character:= bits.TrailingZeros64() / 8|= & (1<<(uint()*8&63) - 1)+= int64()break}|=}if < && [] == '"' {return + 1, stringInfo{firstEscape: int(), nonASCII: &msb != 0}, true, nil}}:= min(+8, )for < {:= []|= uint64()++switch {case < ' ':return , stringInfo{}, false, nilcase > 0:// an escape which is not one ends the string, so that the decoder reports itif !isHexDigit() {return , stringInfo{}, false, nil}--case := falseswitch {case 'u':= 4case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':default:return , stringInfo{}, false, nil}case == '\\':= trueif < 0 {= - 1 - (.cursor + 1)}case == '"':return , stringInfo{firstEscape: int(), nonASCII: &msb != 0}, true, nil}}= - .cursorif < {continue}if !.read() {return 0, stringInfo{}, false, .truncatedValueError()}}}// scanLiteral finds the end of the number, true, false or null at the cursor: the position after true, false or null,// or of the first byte which differs from it, and the position of the first byte which can't belong to the number by// its grammar, or the end of the input. A number is read until a byte ends it, as encoding/json reads it, but a byte// which makes it invalid ends it without a read more. A number ends where its grammar ends it, so that 01 is 0 and then// 1, as encoding/json reads them.func ( *Stream) () (int64, error) {if := literalOf(.buf[.cursor]); != "" {for := 1; < len(); ++ {// a read may bring nothing, and the next one morefor .cursor+int64() >= .length {if !.read() {return .scanLiteralEnd()}}if .buf[.cursor+int64()] != [] {return .cursor + int64() + 1, nil}}return .cursor + int64(len()), nil}// an integer which doesn't start with 0, which most numbers are, ended by a byte in what has been read, without a// call: the nul byte at the end of what has been read stops the digits:= .cursorif .buf[] == '-' {++}if .buf[]-'1' <= 8 {++for .buf[]-'0' <= 9 {++}if := .buf[]; < .length && != '.' && != 'e' && != 'E' {return , nil}}// rel is the end of the digits which end what has been read and continue the number, relative to the cursor, as a// read may move the data, or 0: the digits read after them are skipped, and the number is scanned again from its// start only at another byte, which a number has a few of, so that a long number is scanned in linear timevar int64for {if > 0 {if = int64(jsonnum.ScanDigits(.buf[.cursor:.length], int())); .cursor+ == .length {if !.read() {return .scanLiteralEnd()}continue}}, := jsonnum.Scan(.buf[.cursor:.length])if := .cursor + int64(); < .length {if == jsonnum.Valid {return , nil}// the byte where the number is invalidreturn + 1, nil}= 0if == jsonnum.Valid && digitsContinue(.buf[.cursor:.length]) {= int64()}if !.read() {return .scanLiteralEnd()}}}// scanLiteralEnd returns what scanLiteral returns at the end of the input in a literal: the end of what has been read,// or the error of the reader.func ( *Stream) () (int64, error) {if .readErr != io.EOF {return 0, .readErr}return .length, nil}// digitsContinue reports whether a digit after num, a valid number, belongs to it: after a digit of any number but 0// and -0, whose zero is the whole of the integer part.func digitsContinue( []byte) bool {:= [len()-1]return -'0' <= 9 && !( == '0' && (len() == 1 || len() == 2 && [0] == '-'))}// literalOf returns true, false or null, which c starts, or "".func literalOf( byte) string {switch {case 't':return "true"case 'f':return "false"case 'n':return "null"}return ""}// DecoderOf returns the decoder of the type, from the recent decoders of the context of the stream.func ( *Stream) ( unsafe.Pointer) (Decoder, error) {return .ctx.DecoderOf()}// Decode decodes the next value of the stream into p, of the pointer type typ, by dec. If the value has a type// error, the stream goes on after the value, as the one of encoding/json does.func ( *Stream) ( Decoder, unsafe.Pointer, unsafe.Pointer) error {.markPrevEnd()if := .prepare(); != nil {return}// a value which the buffer doesn't hold whole is decoded element by element, without a read for it ( see// scanCompound ), := .scanValue()if != nil {return .scanFailed(, , , )}:= .ctx.Option = .Optionif (.Option.Flags & NoCopyStringOption) != 0 {// the strings of the value refer to the buffer, which is not reused in place then ( see grow ).referred = true}var int64if := .buf[.cursor]; != 't' && != 'f' && != 'n' {// The end of the value is known exactly: a nul byte is put there while the value is decoded,// so that the decoder never reads the next value, whatever it makes of a malformed one.// A number needs it too, because the decoder validates the byte which ends it.:= .buf[].buf[] = nul.Buf = .buf[:+1].origin = .Buf, = .Decode(, .cursor, 0, ).buf[] =} else {// true, false and null end at the first byte which can't belong to them, and the decoder// reports that byte when it is wrong: it sees the whole buffer, ended by the nul byte..Buf = .buf[:.length+1].origin = .Buf, = .Decode(, .cursor, 0, )}.Buf, .origin = nil, nilif != nil {return .decodeError()}if .HasTypeError() {return .typeError(, )}.cursor =if countsScanned {.scanned += .offset + - .readStart}.more.reset()if .tokenState != tokenTopValue {.tokenValueEnd()}return nil}// callDecoder decodes the value at the cursor, which ends at end, by dec into p, nested in depth objects and arrays,// and returns the position after it. The decoded strings are copied out of the buffer, which they would keep alive,// unless NoCopyStringOption is set.func ( *Stream) ( Decoder, unsafe.Pointer, , int64) (int64, error) {:= .ctxvar int64var errorif := .buf[.cursor]; != 't' && != 'f' && != 'n' {// The end of the value is known exactly: a nul byte is put there while the value is decoded,// so that the decoder never reads the next value, whatever it makes of a malformed one.// A number needs it too, because the decoder validates the byte which ends it.:= .buf[].buf[] = nul.Buf = .buf[:+1].origin = .Buf, = .Decode(, .cursor, , ).buf[] =} else {// true, false and null end at the first byte which can't belong to them, and the decoder// reports that byte when it is wrong: it sees the whole buffer, ended by the nul byte..Buf = .buf[:.length+1].origin = .Buf, = .Decode(, .cursor, , )}.Buf, .origin = nil, nilreturn ,}// decodeError returns the error of the decoder, whose offset is made the one in the whole input, of the value at// the cursor. A type error before it is not kept for the next value.//// A syntax error is the first one of the value by the grammar, as encoding/json reports it: it checks the value// before it decodes it. The decoder never writes the buffer, which keeps the input.////go:noinlinefunc ( *Stream) ( error) error {.ctx.DiscardTypeError()// a syntax error of the value is the error, whatever the decoder met before it, as encoding/json checks the value// before it decodes itif := .valueSyntaxError(); != nil {return .fail()}return .fail(.totalOffsetError())}// valueSyntaxError returns the first syntax error of the value at the cursor by the grammar, in what has been read:// the error of a byte, with its offset in the whole input, or the unexpected end of the input, where encoding/json// reads more. A number, true, false or null is followed by the byte after it, or by the end of the input: the scan// of the value has read either. It is nil if what has been read has none.////go:noinlinefunc ( *Stream) () error {return .valueSyntaxErrorAt(0)}// valueSyntaxErrorAt is valueSyntaxError for a value nested in depth objects and arrays.func ( *Stream) ( int64) error {, := skipValue(.buf[:.length+1], .cursor, )if == nil {return nil}return .grammarError()}// grammarError returns the syntax error err of a scan of the grammar in what has been read, as valueSyntaxError// reports it.func ( *Stream) ( error) error {if errors.IsAtEnd() {return .unexpectedEndError()}if , := errors.ValueStartAt(); {if := .valueStartMismatch(); != nil {return}}return .scannedOffset(.totalOffsetError())}// scannedOffset makes the offset of the syntax error of the value read from readStart the one which encoding/json// of the Go version reports ( see countsScanned ).func ( *Stream) ( error) error {if , := .(*errors.SyntaxError); && countsScanned {.Offset += .scanned - .readStart}return}// typeError returns the type error of the value of the pointer type typ which Decode decoded from the cursor up// to end, and moves the cursor after the value: the stream goes on after it, as the one of encoding/json does.// Its offset is relative to the start of the value, as encoding/json reports it.////go:noinlinefunc ( *Stream) ( unsafe.Pointer, int64) error {:= .cursor.cursor =if countsScanned {.scanned += .offset + - .readStart}.more.reset()if .tokenState != tokenTopValue {.tokenValueEnd()}:= .ctx// the path of the error is walked in the value ended by the nul byte, as it was decoded:= .buf[].buf[] = nul.Buf = .buf[:+1]:= .TypeError(runtime.TypeOfPtr(), , , nil).Buf = nil.buf[] =return}// totalOffsetError makes the offset of an error of the decoder, which is relative to the buffer,// the offset in the whole input.func ( *Stream) ( error) error {switch e := .(type) {case *errors.SyntaxError:.Offset += .offsetcase *errors.UnmarshalTypeError:.Offset += .offset}return}// tokenString decodes the string at the cursor by the string decoder, as Decode does.func ( *Stream) () (any, error) {.readStart = .offset + .cursor, := .scanValue()if != nil {return nil,}:= .buf[].buf[] = nul, , := tokenStringDecoder.decodeByte(.buf[:+1], .cursor).buf[] =if != nil {if := .valueSyntaxError(); != nil {return nil,}return nil, .totalOffsetError()}.cursor =if countsScanned {.scanned += .offset + - .readStart}if len() != 0 && !isPartOf(, .buf) {// the bytes of the escaped string, which decodeLiteral made: they are the string's ownreturn unsafe.String(unsafe.SliceData(), len()), nil}return string(), nil}var tokenStringDecoder = newStringDecoder("", "")
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |