//go:build go1.27 && goexperiment.jsonv2

package decoder

import (
	
	
	
	
	

	
	
)

// 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 {
	case tokenObjectColon:
		return ':'
	case tokenArrayComma, tokenObjectComma:
		if  != '}' &&  != ']' {
			return ','
		}
	}
	return 0
}

// 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() {
		return 0, .tokenEnd()
	}
	var  byte
	 := .TotalOffset()
	if  := .buf[.cursor];  == ',' ||  == ':' {
		 = 
		.cursor++
		if !.skipWhiteSpace() {
			// the next token is not known: a string, which follows any comma or colon, is taken for it
			if .needDelim('"') !=  {
				return 0, .delimError('"', , )
			}
			return 0, .tokenEnd()
		}
	}
	 := .buf[.cursor]
	if .needDelim() !=  {
		// the byte after the white spaces: the comma or the colon, or else the token
		return 0, .delimError(, , )
	}
	switch {
	case  == ',' && .tokenState == tokenArrayComma:
		.tokenState = tokenArrayValue
	case  == ',':
		.tokenState = tokenObjectKey
	case  == ':':
		.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 colon
	for  := max(-.offset, 0);  < .length; ++ {
		switch .buf[] {
		case ' ', '\t', '\n', '\r', ',', ':':
		default:
			return io.ErrUnexpectedEOF
		}
	}
	return io.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:noinline
func ( *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 = , tokenFailed
		return 
	}
	return nil
}

// 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 starts
		if  := .valueStartMismatch( - .offset);  != nil {
			return 
		}
		return .invalidCharacter(, "looking for beginning of value")
	case kindOf() == noValue:
		// a byte which starts no token
		return .invalidCharacter(, "looking for beginning of value")
	case  != '"' && (.tokenState == tokenObjectStart || .tokenState == tokenObjectKey):
		return .memberNameError()
	}
	return nil
}

// 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")
	}
	return nil
}

// 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 
	}
	return errors.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 {
	case tokenArrayComma:
		 = "after array element"
	case tokenObjectComma, 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 = false
	if ,  := .(*errors.UnmarshalTypeError);  == nil ||  {
		// a token is read: InputOffset reports its end again
		.more.reset()
	} else if .tokenState != tokenFailed && .tokenState != tokenEnded {
		.tokenState = 
	}
	return , 
}

// token reads the next token for Token.
func ( *Stream) () (any, error) {
	if .tokenState == tokenFailed || .tokenState == tokenEnded {
		return nil, .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, 
			return nil, 
		}
		return nil, .restore(, )
	}
	 := .TotalOffset()
	switch  {
	case '[', '{':
		if .tokenState == tokenObjectStart || .tokenState == tokenObjectKey {
			return nil, .restore(, errors.ErrSyntax("object member name must be a string", +1))
		}
		.cursor++
		.tokenStack = append(.tokenStack, .tokenState)
		if  == '[' {
			.tokenState = tokenArrayStart
		} else {
			.tokenState = tokenObjectStart
		}
		return json.Delim(), nil
	case ']', '}':
		 := tokenArrayStart
		if  == '}' {
			 = tokenObjectStart
		}
		if len(.tokenStack) == 0 || !.inOpen() {
			return nil, .restore(, .mismatchError())
		}
		if .tokenState == tokenObjectValue {
			return nil, .restore(, errors.ErrSyntax("missing value after object key", +1))
		}
		.cursor++
		.tokenState = .tokenStack[len(.tokenStack)-1]
		.tokenStack = .tokenStack[:len(.tokenStack)-1]
		.tokenValueEnd()
		return json.Delim(), nil
	case '"':
		if .tokenState == tokenObjectStart || .tokenState == tokenObjectKey {
			,  := .tokenString()
			if  != nil {
				return nil, .restore(, )
			}
			.tokenState = tokenObjectColon
			return , nil
		}
	default:
		if kindOf() != noValue && (.tokenState == tokenObjectStart || .tokenState == tokenObjectKey) {
			return nil, .restore(, .memberNameError())
		}
	}
	,  := .tokenValue()
	if  != nil {
		if ,  := .(*errors.UnmarshalTypeError);  {
			// the value is read: the stream goes on after it
			.tokenValueEnd()
			return nil, 
		}
		return nil, .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 {
	case tokenArrayStart, 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 it
		return .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[]
	var  byte
	if  == ',' ||  == ':' {
		 = 
		if ,  = .peekFrom( + 1); ! {
			// the next token is not known: a string, which follows any comma or colon, is taken for it
			if .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 )
	 :=  - .cursor
	for {
		for  = .cursor + ;  < .length; ++ {
			if !isWhiteSpace[.buf[]] {
				return , true
			}
		}
		 = .length - .cursor
		if !.read() {
			return 0, 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 {
	if len(.tokenStack) == 0 {
		return false
	}
	// 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), , tokenFailed
	return true
}

// 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(), tokenFailed
	return true
}

func trimLeftSpaces( []byte) []byte {
	for len() > 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 {
			return nil, 
		}
		// 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 {
			return nil, .valueSyntaxError()
		}
		 := .buf[.cursor : .cursor+int64()]
		.cursor += int64()
		if (.Option.Flags & UseNumberOption) != 0 {
			return json.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 it
			return nil, &errors.UnmarshalTypeError{Value: "number " + string(), Type: float64Type, Offset: .TotalOffset()}
		}
		return , nil
	case 't', 'f', 'n':
		,  := .scanValue()
		if  != nil {
			return nil, 
		}
		var  any
		 := "null"
		switch  {
		case 't':
			,  = true, "true"
		case 'f':
			,  = false, "false"
		}
		// the literal ends after its bytes: what follows is the next token
		if !bytes.HasPrefix(.buf[.cursor:], []byte()) {
			return nil, .valueSyntaxError()
		}
		.cursor += int64(len())
		return , nil
	}
	return nil, .tokenError()
}