//go:build go1.27 && goexperiment.jsonv2package decoderimport ()// The tokens of a stream as encoding/json of Go 1.27 reads them, by encoding/json/jsontext: a token or a value is// read after the comma or the colon which the grammar has before it, which is checked against the kind of the// token, and a read which fails leaves the stream where it was. A value may be read where a key is waited for,// as the key.// streamPeek is what More peeked at: encoding/json of Go 1.27 reports by InputOffset the start of the next token// after More, until a value or a token is read.type streamPeek struct {// peeked is whether More was called after the last value or token which was read. peeked bool// offset is the total offset of the next token which More peeked at, or of the end of the value or the token // before it if the input has none. offset int64}// reset forgets what More peeked at, after a value or a token is read.func ( *streamPeek) () { .peeked = false}// countsScanned is whether the offset of a syntax error of a value of Decode is counted from the bytes which the// reads of the values read: encoding/json of Go 1.27 reports the offset in the whole input.const countsScanned = false// invalidCharacter returns the syntax error of the character at the total offset, which the grammar doesn't// have where it is: encoding/json of Go 1.27 reports the rune there, of the bytes which have been read, without a// read for the rest of it.func ( *Stream) ( int64, string) error { := invalidCharacterError(.buf[:.length+1], -.offset, )return .totalOffsetError()}// tokenEnded is after Token read the end of the input: every read returns io.EOF.const tokenEnded = tokenFailed + 1// needDelim returns the comma or the colon which the grammar has before a token of the kind which starts with c,// or 0 for none.func ( *Stream) ( byte) byte {switch .tokenState {casetokenObjectColon:return':'casetokenArrayComma, tokenObjectComma:if != '}' && != ']' {return',' } }return0}// readDelim reads, from start, the white spaces and the comma or the colon before the next token, which it checks// against the token, and moves the state after it. It returns the byte which starts the token.func ( *Stream) ( int64) (byte, error) {if !.peek() {return0, .tokenEnd() }varbyte := .TotalOffset()if := .buf[.cursor]; == ',' || == ':' { = .cursor++if !.skipWhiteSpace() {// the next token is not known: a string, which follows any comma or colon, is taken for itif .needDelim('"') != {return0, .delimError('"', , ) }return0, .tokenEnd() } } := .buf[.cursor]if .needDelim() != {// the byte after the white spaces: the comma or the colon, or else the tokenreturn0, .delimError(, , ) }switch {case == ',' && .tokenState == tokenArrayComma: .tokenState = tokenArrayValuecase == ',': .tokenState = tokenObjectKeycase == ':': .tokenState = tokenObjectValue }return , nil}// delimError returns the error of the byte at the total offset at, which is not the comma or the colon which the// grammar has before a token which starts with next: delim, the comma or the colon read there, or else the token. The// delimiter is not looked at in the buffer, which a read of the white space after it may have dropped it from.func ( *Stream) (, byte, int64) error { := "looking for beginning of value"switch .needDelim() {case':': = "after object key"case',':if .tokenState == tokenObjectComma { = "after object key:value pair" } else { = "after array element" } }if == 0 {return .invalidCharacter(, ) } := invalidCharacterError([]byte{, nul}, 0, ) .Offset += return}// tokenEnd returns the error of the end of the input before a token: io.EOF if what is left is white spaces,// commas and colons, which a value may follow, as encoding/json reports it.func ( *Stream) ( int64) error {if := .endError(); != io.EOF {return }// the bytes from start which a read dropped from the buffer are white spaces and a comma or a colonfor := max(-.offset, 0); < .length; ++ {switch .buf[] {case' ', '\t', '\n', '\r', ',', ':':default:returnio.ErrUnexpectedEOF } }returnio.EOF}// restore moves the stream back to the total offset start, where a read which failed started, which InputOffset// reports, and returns err.func ( *Stream) ( int64, error) error { .moveBack()return}// moveBack moves the stream back to the total offset start, where a read which failed started, which InputOffset// reports.func ( *Stream) ( int64) {if >= .offset { .cursor = - .offset } .errOffset = }// prepareInTokens moves the cursor to the value which Decode reads between the tokens: after the comma or the// colon which the grammar has before it. A read which fails is kept, as encoding/json keeps it. It is not// inlined, so that Decode keeps the size it had.////go:noinlinefunc ( *Stream) () error {if .tokenState == tokenFailed || .tokenState == tokenEnded {return .err } := .TotalOffset() , := .readDelim()if == nil { = .valueStartError() }if != nil {if == io.EOF {// the end of the input in an object or an array = io.ErrUnexpectedEOF } .moveBack() .err, .tokenState = , tokenFailedreturn }returnnil}// valueStartError returns the error of a value which starts with c where it can't be read: the end of an object or// an array, or a value which is not a string where a key is waited for.func ( *Stream) ( byte) error { := .TotalOffset()switch {case == '}' || == ']':// a bracket where the value startsif := .valueStartMismatch( - .offset); != nil {return }return .invalidCharacter(, "looking for beginning of value")casekindOf() == noValue:// a byte which starts no tokenreturn .invalidCharacter(, "looking for beginning of value")case != '"' && (.tokenState == tokenObjectStart || .tokenState == tokenObjectKey):return .memberNameError() }returnnil}// valueStartMismatch returns the error of the bracket at the position at in the buffer, where a value is waited for// in the value which is read or where it starts, if it is the end of the other kind of the object or the array// which Token opened last, which has a member or an element already: jsontext reports it as a mismatch of that// one, whatever the value is in. It returns nil for any other one, which is not the start of a value.func ( *Stream) ( int64) error {switch := .buf[]; {case == ']' && (.tokenState == tokenObjectKey || .tokenState == tokenObjectColon || .tokenState == tokenObjectValue || .tokenState == tokenObjectComma):return .invalidCharacter(.offset+, "after object key:value pair")case == '}' && (.tokenState == tokenArrayValue || .tokenState == tokenArrayComma):return .invalidCharacter(.offset+, "after array element") }returnnil}// memberNameError returns the error of the value at the cursor, at the total offset at, where the name of a member// of an object is waited for: the value is read first, as jsontext reads a value or a token, and its syntax error,// or the end of the input in it, is the error; else the name is not a string.func ( *Stream) ( int64) error {if , := .wholeEnd(0); != nil {return }returnerrors.ErrSyntax("object member name must be a string", +1)}// mismatchError returns the error of the end of an object or an array c at the total offset at, which doesn't end// the one which is open.func ( *Stream) ( int64) error { := "looking for beginning of value"switch .tokenState {casetokenArrayComma: = "after array element"casetokenObjectComma, tokenObjectValue:// a bracket where a value of an object is waited for too, as jsontext reports it = "after object key:value pair" }return .invalidCharacter(, )}// Token returns the next token of the stream: a delimiter, a string, a number, a bool or nil. The commas and the// colons are consumed where the grammar has them.func ( *Stream) () (any, error) {// a read which fails leaves the stream where it was, in its state, with the bytes from where it was := .tokenState .keeps, .keepFrom = true, .TotalOffset() , := .token() .keeps = falseif , := .(*errors.UnmarshalTypeError); == nil || {// a token is read: InputOffset reports its end again .more.reset() } elseif .tokenState != tokenFailed && .tokenState != tokenEnded { .tokenState = }return , }// token reads the next token for Token.func ( *Stream) () (any, error) {if .tokenState == tokenFailed || .tokenState == tokenEnded {returnnil, .err } := .TotalOffset() , := .readDelim()if != nil {if == io.EOF {// InputOffset reports a comma or a colon before the end, with the white spaces before it, and not the // white spaces at the end .moveBack()if := trimLeftSpaces(.buf[.cursor:.length]); len() > 0 && ([0] == ',' || [0] == ':') { .errOffset = .TotalOffset() + int64(len(.buf[.cursor:.length])-len()) + 1 } .tokenState, .err = tokenEnded, returnnil, }returnnil, .restore(, ) } := .TotalOffset()switch {case'[', '{':if .tokenState == tokenObjectStart || .tokenState == tokenObjectKey {returnnil, .restore(, errors.ErrSyntax("object member name must be a string", +1)) } .cursor++ .tokenStack = append(.tokenStack, .tokenState)if == '[' { .tokenState = tokenArrayStart } else { .tokenState = tokenObjectStart }returnjson.Delim(), nilcase']', '}': := tokenArrayStartif == '}' { = tokenObjectStart }iflen(.tokenStack) == 0 || !.inOpen() {returnnil, .restore(, .mismatchError()) }if .tokenState == tokenObjectValue {returnnil, .restore(, errors.ErrSyntax("missing value after object key", +1)) } .cursor++ .tokenState = .tokenStack[len(.tokenStack)-1] .tokenStack = .tokenStack[:len(.tokenStack)-1] .tokenValueEnd()returnjson.Delim(), nilcase'"':if .tokenState == tokenObjectStart || .tokenState == tokenObjectKey { , := .tokenString()if != nil {returnnil, .restore(, ) } .tokenState = tokenObjectColonreturn , nil }default:ifkindOf() != noValue && (.tokenState == tokenObjectStart || .tokenState == tokenObjectKey) {returnnil, .restore(, .memberNameError()) } } , := .tokenValue()if != nil {if , := .(*errors.UnmarshalTypeError); {// the value is read: the stream goes on after it .tokenValueEnd()returnnil, }returnnil, .restore(, ) } .tokenValueEnd()return , nil}// inOpen reports whether the innermost object or array which is open is of the kind of the state open.func ( *Stream) ( tokenState) bool {switch .tokenState {casetokenArrayStart, tokenArrayValue, tokenArrayComma:return == tokenArrayStart }return == tokenObjectStart}// tokenError returns the syntax error of the byte c at the cursor, which the grammar doesn't have in the state.func ( *Stream) ( byte) error {return .invalidCharacter(.TotalOffset(), "looking for beginning of value")}// InputOffset returns the offset of the stream which Decoder.InputOffset reports: the end of the last token or// value read, or where a read which failed started.func ( *Stream) () int64 { := .TotalOffset()if .tokenState == tokenFailed || .tokenState == tokenEnded { = .errOffset }if .more.peeked {// after More, the start of the next token which it peeked at, after the white spaces before itreturn .more.offset }return}// More reports whether the current array or object has another element: at the end of the input in one, it// reports true, and the error of the end is returned by the next read, as encoding/json of Go 1.27 does.func ( *Stream) () bool {if .tokenState == tokenFailed || .tokenState == tokenEnded {return .err != io.EOF }// the next token is peeked at, with the comma or the colon before it, as Token reads it: the cursor is kept, // so that the bytes from it stay in the buffer while more input is read := .TotalOffset() .more.peeked, .more.offset = true, , := .peekFrom(.cursor)if ! {return .moreAtEnd() } .more.offset = .offset + , := .offset+, .buf[]varbyteif == ',' || == ':' { = if , = .peekFrom( + 1); ! {// the next token is not known: a string, which follows any comma or colon, is taken for itif .needDelim('"') != {return .moreError(.delimError('"', , )) }return .moreAtEnd() } = .buf[] }if .needDelim() != {return .moreError(.delimError(, , )) }return != ']' && != '}'}// peekFrom returns the position of the first byte from pos which is not a white space, reading more input as// needed without moving the cursor, or false at the end of the input.func ( *Stream) ( int64) (int64, bool) {// the position is kept relative to the cursor, because a read may move the data ( grow ) := - .cursorfor {for = .cursor + ; < .length; ++ {if !isWhiteSpace[.buf[]] {return , true } } = .length - .cursorif !.read() {return0, false } }}// moreAtEnd returns what More reports at the end of the input, which it peeked at from the total offset start: the// end of a stream of values, or the unexpected end of an object or an array, which is kept as the error.func ( *Stream) ( int64) bool {iflen(.tokenStack) == 0 {returnfalse }// the error is at the end of the input, after the white spaces, which InputOffset doesn't report .err, .errOffset, .tokenState = errors.ErrSyntax("unexpected end of JSON input", .offset+.length), , tokenFailedreturntrue}// moreError keeps err, the error of the token which More peeked at, which encoding/json of Go 1.27 reads, and// returns true.func ( *Stream) ( error) bool { .err, .errOffset, .tokenState = , .TotalOffset(), tokenFailedreturntrue}func trimLeftSpaces( []byte) []byte {forlen() > 0 && ([0] == ' ' || [0] == '\t' || [0] == '\n' || [0] == '\r') { = [1:] }return}// tokenValue returns the value at the cursor, which starts with c, as the token of a string, a number, a bool or// null.func ( *Stream) ( byte) (any, error) {switch {case'"':return .tokenString()case'-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': , := .scanValue()if != nil {returnnil, }// the number ends where the grammar ends it, as 01 is 0 and 1, and is a number by the grammar , := jsonnum.Scan(.buf[.cursor:])if != jsonnum.Valid {returnnil, .valueSyntaxError() } := .buf[.cursor : .cursor+int64()] .cursor += int64()if (.Option.Flags & UseNumberOption) != 0 {returnjson.Number(), nil } , := jsonnum.ParseFloat()if ! { , = strconv.ParseFloat(*(*string)(unsafe.Pointer(&)), 64) }if != nil {// a number out of the range of float64, which is read: a type error of the value, which Token // returns after itreturnnil, &errors.UnmarshalTypeError{Value: "number " + string(), Type: float64Type, Offset: .TotalOffset()} }return , nilcase't', 'f', 'n': , := .scanValue()if != nil {returnnil, }varany := "null"switch {case't': , = true, "true"case'f': , = false, "false" }// the literal ends after its bytes: what follows is the next tokenif !bytes.HasPrefix(.buf[.cursor:], []byte()) {returnnil, .valueSyntaxError() } .cursor += int64(len())return , nil }returnnil, .tokenError()}
The pages are generated with Goldsv0.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.