package jsontext

import (
	
	
	
	

	
	
)

// Decoder is a streaming decoder of raw JSON tokens and values. It reads a stream of top-level JSON values,
// separated by optional white space.
//
// Decoder.ReadToken and Decoder.ReadValue calls may be interleaved. For example, the JSON value
//
//	{"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}}
//
// can be read by these calls (ignoring errors):
//
//	d.ReadToken() // {
//	d.ReadToken() // "name"
//	d.ReadToken() // "value"
//	d.ReadValue() // "array"
//	d.ReadToken() // [
//	d.ReadToken() // null
//	d.ReadToken() // false
//	d.ReadValue() // true
//	d.ReadToken() // 3.14159
//	d.ReadToken() // ]
//	d.ReadValue() // "object"
//	d.ReadValue() // {"k":"v"}
//	d.ReadToken() // }
//
// which is one of many sequences of calls which read it.
type Decoder struct {
	d decoder
}

// decoder is the state of a Decoder.
type decoder struct {
	cfg config
	st  stack
	vs  valueScanner

	r      io.Reader
	bb     *bytes.Buffer // r, which is read in place
	buf    []byte        // the input which was read and is kept: from the last token or value on
	shared bool          // buf is the array of bb, which the decoder must not write to
	base   int64         // the offset of buf[0] in the input

	pos                int   // the read offset: the end of the last token or value
	prevStart, prevEnd int   // the last token or value, whose start may be before the buffer ( see endValue )
	rerr               error // the error of the reader in the current call
	peekErr            error // an error which PeekKind found, which the next read reports

	raw tokenSource // the source of its raw tokens
}

// NewDecoder constructs a streaming decoder which reads from r.
//
// If r is a bytes.Buffer, the decoder reads the buffer in place, without copying its contents. The buffer must
// not be written to while the decoder is used.
func ( io.Reader,  ...Options) *Decoder {
	 := new(Decoder)
	.Reset(, ...)
	return 
}

// Reset resets the decoder to read from r anew, with the options.
func ( *Decoder) ( io.Reader,  ...Options) {
	switch {
	case  == nil:
		panic("jsontext: invalid nil Decoder")
	case  == nil:
		panic("jsontext: invalid nil io.Reader")
	}
	.d.reset(, )
}

// ready reports whether the decoder is set up: the source of its tokens points to it.
func ( *decoder) () bool { return .raw.dec ==  }

// setUp sets up a decoder which is not ready: a zero value, as one whose input is empty, as
// encoding/json/jsontext takes it, or a copy of a decoder, which takes pointers and arrays of its own: it reads
// on its own as a copy of a decoder of encoding/json/jsontext does, and the decoder it was copied from keeps its
// state.
func ( *decoder) () {
	if len(.st.levels) == 0 {
		.reset(nil, nil)
		return
	}
	.raw.dec = 
	.vs.st = &.st
	.st.own()
	if !.shared {
		.buf = slices.Clone(.buf) // the input which the decoder moves and reads into
	}
	.vs.scratch = nil
}

// reset resets the decoder to read from r, which is nil for no input, with the options.
func ( *decoder) ( io.Reader,  []Options) {
	var  config // opts may hold the options of d, which Options returned
	.Apply()
	.cfg = 
	if !.ready() {
		// a zero value, or a copy, whose arrays are the ones of the decoder it was copied from
		.st, .vs.scratch = stack{}, nil
		if !.shared {
			.buf = nil
		}
	}
	.st.reset()
	if .st.outer != nil {
		.st.outer, .st.outerDepth, .st.outerCount = nil, 0, 0 // of an attach by the v2 json package
	}
	if ,  := .r.(*bytes.Buffer); .shared ||  {
		// the buffer of a bytes.Buffer which was read before is dropped, as encoding/json/jsontext drops it
		.buf, .shared = nil, false
	}
	.r = 
	.bb, _ = .(*bytes.Buffer)
	.buf = .buf[:0]
	.base, .pos, .prevStart, .prevEnd = 0, 0, 0, 0
	.rerr, .peekErr = nil, nil
	.raw = tokenSource{dec: , form: formRaw}
	.vs = valueScanner{
		st:                   &.st,
		validUTF8:            !.cfg.Has(allowInvalidUTF8),
		rejectDuplicateNames: !.cfg.Has(allowDuplicateNames),
		decoding:             true,
		scratch:              .vs.scratch[:0],
	}
}

// Options returns the options of the decoder: the ones it was constructed or last reset with, which follow a
// later Reset.
func ( *Decoder) () Options {
	return &.d.cfg
}

func ( *decoder) () int64  { return .base + int64(.prevStart) }
func ( *decoder) () []byte { return .buf[.prevStart:.prevEnd] }

// minRead is the room which the buffer has for a read.
const minRead = 512

// fetch reads more input to the end of the buffer. It may move the buffer, and drop the input before the last
// token: it returns the number of bytes by which the positions in the buffer moved back. At the end of the
// input, it returns io.EOF, and at an error of the reader, the error in an ioError.
func ( *decoder) () (int, error) {
	if .rerr != nil {
		return 0, .rerr
	}
	if .r == nil {
		.rerr = io.EOF // a zero value
		return 0, io.EOF
	}
	if .bb != nil {
		switch {
		case .bb.Len() == 0:
			.rerr = io.EOF
			return 0, io.EOF
		case .shared:
			// the buffer was written to after the decoder took its array, which the write may have changed: the
			// input is left in the buffer.
			.rerr = &ioError{err: errBufferWriteAfterNext}
			return 0, .rerr
		}
		 := .bb.Next(.bb.Len())
		if len(.buf) == 0 {
			.buf, .shared = , true
			return 0, nil
		}
		 := .makeRoom(len())
		.buf = append(.buf, ...)
		return , nil
	}
	 := 0
	if cap(.buf)-len(.buf) < minRead+textcoder.InputRoom || .shared {
		 = .makeRoom(minRead + textcoder.InputRoom)
	}
	for {
		// the room after the input is left to a caller which reads the buffer in place ( see textcoder.InputRoom )
		,  := .r.Read(.buf[len(.buf) : cap(.buf)-textcoder.InputRoom])
		if  > 0 {
			// an error which comes with input is dropped, as encoding/json/jsontext drops it: the reader reports
			// it again at the next read, if it lasts.
			.buf = .buf[:len(.buf)+]
			return , nil
		}
		if  == nil {
			continue // no input, which encoding/json/jsontext reads again for, as long as it takes
		}
		if ,  := .r.(*failedInput); ! &&  != io.EOF {
			// but the error of a decoder which failed, which is returned as it is
			 = &ioError{err: }
		}
		.rerr = 
		return , 
	}
}

// makeRoom makes room for n more bytes at the end of the buffer, dropping the input before the last token only
// when the buffer is full, so that each byte is moved a few times at most. It returns by how much the
// positions moved back.
func ( *decoder) ( int) int {
	if cap(.buf)-len(.buf) >=  && !.shared {
		return 0
	}
	// the start of the last token, or of the buffer if it is before the buffer
	 := max(.prevStart, 0)
	 := len(.buf) - 
	if + <= cap(.buf) && !.shared {
		copy(.buf, .buf[:])
		.buf = .buf[:]
	} else {
		 := make([]byte, , max(2*cap(.buf), +, 4096))
		copy(, .buf[:])
		.buf, .shared = , false
	}
	.base += int64()
	.pos -= 
	.prevStart -= 
	.prevEnd -= 
	return 
}

// skip returns the position of the first byte from pos which is not white space, reading more input as it
// needs. At the end of the input, it returns the error of the reader.
func ( *decoder) ( int) (int, error) {
	for {
		if  = skipSpace(.buf, );  < len(.buf) {
			return , nil
		}
		,  := .fetch()
		 -= 
		if  != nil {
			return , 
		}
	}
}

// charError is the error of the invalid character at pos, which is not expected at the place. A
// character which the buffer cuts is read whole first, so that the error shows it as the input has it.
func ( *decoder) ( int,  charPlace,  int) error {
	for .rerr == nil && !utf8.FullRune(.buf[:]) {
		,  := .fetch()
		 -= 
	}
	return .failAt(invalidChar(.buf[:], ), , )
}

// failAt is a SyntacticError at the position pos of the buffer, in the value where points.
func ( *decoder) ( error,  int,  int) error {
	return &SyntacticError{ByteOffset: .base + int64(), JSONPointer: .st.pointer(), Err: }
}

// endError is the error at the end of the input at pos: io.EOF where a top-level value may start, or else an
// unexpected one. A reader error which is not io.EOF is returned as it is.
func ( *decoder) ( int,  error,  int) error {
	if  != io.EOF {
		return 
	}
	if .st.depth() == 0 &&  == skipSpace(.buf, .pos) &&  != pointNext {
		return io.EOF
	}
	return .failAt(io.ErrUnexpectedEOF, , )
}

// PeekKind returns the kind of the next token, without reading it.
//
// It returns KindInvalid at an error, which it keeps for the next read call to report: a PeekKind call must
// be followed by a read call.
func ( *Decoder) () Kind {
	 := &.d
	if !.ready() {
		.setUp()
	}
	.invalidate()
	,  := .beforeToken(true)
	.peekErr = nil // an error of an earlier PeekKind is replaced
	if  != nil {
		.peekErr =  // even io.EOF, which the next read reports once
		return KindInvalid
	}
	return kindOf(.buf[])
}

// beforeToken skips the white space and the delimiter before the next token, and returns its position. peek is
// set for PeekKind, which takes an end delimiter of any kind: the read which follows checks it.
//
// A comma or a colon is taken first, and then compared with the delimiter which the next token needs: one which
// is not needed, or not the one needed, is an invalid character itself.
func ( *decoder) ( bool) (int, error) {
	// an error of the reader, even io.EOF, ends only the call which met it: the next one reads again.
	.rerr = nil
	// most tokens have the delimiter which they need, with some white space, in the buffer.
	 := .buf
	if  := skipWS(, .pos);  < len() {
		 := []
		 := .delimBefore(, )
		if  != ',' &&  != ':' {
			if  == 0 {
				return , nil
			}
		} else if  ==  {
			if  := skipWS(, +1);  < len() {
				if  := [];  != ',' &&  != ':' && ( != '}' &&  != ']' ||  == ':') && .delimBefore(, ) ==  {
					return , nil
				}
			}
		}
	}
	,  := .skip(.pos)
	if  != nil {
		return , .endError(, , pointAt)
	}
	,  := byte(0), 
	 := .delimBefore(.buf[], )
	if  := .buf[];  == ',' ||  == ':' {
		 = 
		 := .base
		,  = .skip( + 1)
		 -= int(.base - ) // the input which a fetch dropped
		if  != nil {
			// at the end of the input, or an error of the reader, a delimiter which the next token can't need is
			// reported first
			if  ==  {
				return , .endError(, , pointAt)
			}
		} else if  := .buf[]; ( == '}' ||  == ']') && !.st.last().needValue() {
			 = 0 // before an end delimiter of any kind, a delimiter is the error
		} else {
			 = .delimBefore(, )
		}
	}
	switch {
	case  == :
		return , nil
	case  == 0:
		return , .missingDelim()
	case  == 0:
		return , .charError(, placeStartOfValue, pointAt)
	default:
		// the delimiter of the other kind is reported as the character where the needed one is
		return , .missingDelim()
	}
}

// delimBefore is the delimiter which the next token, which starts with c, needs before it: a comma, a colon, or
// none.
func ( *decoder) ( byte,  bool) byte {
	 := .st.last()
	switch {
	case .st.depth() == 0:
		return 0
	case .needValue():
		return ':'
	case .count == 0:
		return 0
	case  == '}' && (.object || ),  == ']' && (!.object || ):
		return 0 // the end
	}
	return ','
}

// missingDelim is the error of the character at pos, where a delimiter is needed.
func ( *decoder) ( int) error {
	 := .st.last()
	switch {
	case .needValue():
		return .charError(, placeAfterObjectName, pointAt)
	case .object:
		// the end of an array in an object is reported in the level which contains the object.
		 := pointAt
		if .buf[] == ']' {
			 = pointOut
		}
		return .charError(, placeAfterObjectValue, )
	}
	return .charError(, placeAfterArrayElement, pointAt)
}

// ReadToken reads the next Token and advances the read offset. The token is only valid until the next Peek,
// Read or Skip call. It returns io.EOF at the end of the input.
func ( *Decoder) () (Token, error) {
	return .d.readToken()
}

// readToken reads the next token in one loop where the token and the delimiter before it are valid and whole in
// the buffer, as most tokens are, and else by readTokenSlow, from the same state.
func ( *decoder) () (Token, error) {
	if !.ready() {
		.setUp()
	}
	.invalidate()
	 := .buf
	 := skipWS(, .pos)
	if  >= len() || len(.st.levels) == 1 || .peekErr != nil {
		return .readTokenSlow() // the top level, which reads a stream of values, among others
	}
	 := &.st.levels[len(.st.levels)-1]
	 := []
	switch {
	case  == '}' && .object && .count%2 == 0,  == ']' && !.object:
		if len(.st.levels)-1 == .st.outerDepth {
			return .readTokenSlow() // the level an attached decoder is in
		}
		.st.pop()
		.done(+1, +1)
		if  == '}' {
			return EndObject, nil
		}
		return EndArray, nil
	case .count == 0:
	case  == ',' && (!.object || .count%2 == 0),  == ':' && .object && .count%2 == 1:
		if  = skipWS(, +1);  >= len() || [] == '}' || [] == ']' {
			return .readTokenSlow()
		}
		 = []
	default:
		return .readTokenSlow()
	}
	 := .object && .count%2 == 0
	switch  {
	case '"':
		,  := simpleStringEnd([:])
		,  := strFlags(0), error(nil)
		if ! {
			, ,  = scanStringFrom([:], , 0, strModeOf(!.cfg.Has(allowInvalidUTF8), true))
		}
		if  != nil ||  && !.st.insertName(unquotedName(&.vs.scratch, [:+], ), !.cfg.Has(allowDuplicateNames)) {
			return .readTokenSlow()
		}
		.count++
		.done(, +)
		return Token{src: &.raw, num: uint64(.base + int64())}, nil
	case '{', '[':
		if  || .st.push( == '{') != nil {
			return .readTokenSlow()
		}
		.done(+1, +1)
		if  == '{' {
			return BeginObject, nil
		}
		return BeginArray, nil
	case 'n', 't', 'f':
		 := literalOf(Kind())
		if  || len()- <= len() || string([:+len()]) !=  {
			return .readTokenSlow()
		}
		.count++
		.done(+len(), +len())
		return literalToken(Kind()), nil
	}
	 := jsonnum.End([:])
	if  ||  < 0 {
		return .readTokenSlow()
	}
	.count++
	.done(, +)
	return Token{src: &.raw, num: uint64(.base + int64())}, nil
}

func ( *decoder) () (Token, error) {
	if  := .peekErr;  != nil {
		.peekErr = nil
		return Token{}, 
	}
	,  := .beforeToken(false)
	if  != nil {
		return Token{}, 
	}
	 := .st.last()
	 := .buf[]
	switch  {
	case '{', '[':
		if .needName() {
			return Token{}, .failAt(ErrNonStringName, , pointAt)
		}
		if  := .st.push( == '{');  != nil {
			return Token{}, .failAt(, , pointNext)
		}
		.done(+1, +1)
		if  == '{' {
			return BeginObject, nil
		}
		return BeginArray, nil
	case '}', ']':
		if  := .closeError();  != nil {
			return Token{}, 
		}
		.st.pop()
		.done(+1, +1)
		if  == '}' {
			return EndObject, nil
		}
		return EndArray, nil
	}
	 := .needName()
	 := pointNext
	if  {
		 = pointAt
	}
	, , ,  := .scanToken(, )
	if  != nil {
		return Token{}, 
	}
	if  {
		if  != '"' {
			return Token{}, .failAt(ErrNonStringName, , pointAt)
		}
		if  := .insertName(, , );  != nil {
			return Token{}, 
		}
	}
	.st.last().count++
	if  := kindOf();  != KindString &&  != KindNumber {
		.done(, ) // a literal isn't in the buffer after
		return literalToken(), nil
	}
	.done(, )
	return Token{src: &.raw, num: uint64(.base + int64())}, nil
}

// closeError is the error of the end delimiter at pos, or nil if it closes the innermost object or array.
func ( *decoder) ( int) error {
	 := .st.last()
	 := .buf[]
	switch {
	case .st.depth() == 0:
		return .charError(, placeStartOfValue, pointAt)
	case .st.outer != nil && .st.depth() == .st.outerDepth:
		// the level a decoder attached at the place of a value is in, which is not a part of the value
		return .failAt(errEndOfReadPlace, , pointAt)
	case .object != ( == '}'):
		if .needValue() {
			return .charError(, placeAfterObjectValue, pointHere)
		}
		if .object {
			return .charError(, placeStartOfValue, pointAt)
		}
		return .charError(, placeStartOfValue, pointNext)
	case .needValue():
		return .failAt(errMissingValue, , pointAt)
	}
	return nil
}

// done records the token or value at buf[start:end] as the last one read.
func ( *decoder) (,  int) {
	.prevStart, .prevEnd, .pos = , , 
}

// invalidate voids the last token or value, as every call which reads does, even one which fails, as
// encoding/json/jsontext does to catch a use of it: a raw Token of it panics, and the first byte of a Value of it
// is overwritten. The input of a bytes.Buffer, whose array the decoder reads, and an input which the decoder
// doesn't own stay as they are.
func ( *decoder) () {
	if .bb == nil && !.shared && .prevEnd > .prevStart {
		if .prevStart >= 0 {
			.buf[.prevStart] = '#'
		}
		.prevStart = .prevEnd
	}
}

// insertName adds the name of the string at buf[start:end] to the innermost object.
func ( *decoder) (,  int,  strFlags) error {
	 := unquotedName(&.vs.scratch, .buf[:], )
	if !.st.insertName(, !.cfg.Has(allowDuplicateNames)) {
		 := .st.namePointer()
		return &SyntacticError{ByteOffset: .base + int64(), JSONPointer: , Err: ErrDuplicateName}
	}
	return nil
}

// unquotedName is the value of the string s, which scanString took with the flags f: the bytes between its quotes,
// or, if it has escape sequences or invalid UTF-8, its value unquoted in scratch.
func unquotedName( *[]byte,  []byte,  strFlags) []byte {
	if &(strEscaped|strInvalidUTF8) != 0 {
		* = appendUnquoted((*)[:0], , )
		return *
	}
	return [1 : len()-1]
}

// scanToken scans the string, number or literal at pos, reading more input while the buffer cuts it. It
// returns the position of the token, which a read may have moved, and its end.
func ( *decoder) ( int,  int) (int, int, strFlags, error) {
	var (
		   int
		   strFlags
		  numState
		 error
	)
	 := .buf[]
	 := !.cfg.Has(allowInvalidUTF8)
	// most tokens are whole in the buffer
	switch  {
	case '"':
		if , ,  := scanString(.buf[:], strModeOf(, true));  == nil {
			return ,  + , , nil
		}
	case 'n', 't', 'f':
	default:
		if kindOf() != KindNumber {
			if ( == ',' ||  == ':') && .st.last().count == 0 {
				 = pointAt // a delimiter before the first value
			}
			return , , 0, .charError(, placeStartOfValue, )
		}
		if  := jsonnum.End(.buf[:]);  > 0 {
			return ,  + , 0, nil
		}
	}
	for {
		 := .buf[:]
		var  bool     // the token may continue after the buffer
		var  bool // an invalid character which the buffer cuts, read again to show it whole
		switch  {
		case '"':
			if  > 0 && plainEnd(, ) == len() {
				// plain characters continue the string to the end of the buffer, as a slow reader gives them
				,  = len(), true
				break
			}
			, ,  = scanStringFrom(, max(, 1), , strModeOf(, .rerr != io.EOF))
			 =  == io.ErrUnexpectedEOF
		case 'n', 't', 'f':
			,  = scanLiteral(, literalOf(Kind()))
			 =  == io.ErrUnexpectedEOF
		default:
			if .inDigits() &&  > 0 {
				if  := jsonnum.ScanDigits(, );  == len() {
					// digits continue the number to the end of the buffer, as a slow reader gives them
					, .done,  = , , true
					break
				}
			}
			, ,  = scanNumberFrom(, , )
			 =  == nil &&  == len() ||  == io.ErrUnexpectedEOF
		}
		if  && .rerr != io.EOF {
			// the token continues after the buffer
			if  == 'n' ||  == 't' ||  == 'f' {
				 = 0
			}
		} else if ,  := .(*textError);  && .rerr == nil && !utf8.FullRune([:]) {
			// an invalid character which the buffer cuts is shown whole: the token is scanned again with more
			 = true
			, ,  = 0, 0, numState{}
		} else {
			break
		}
		,  := .fetch()
		 -= 
		if  != nil &&  != io.EOF {
			if  {
				continue // the error which the input read shows, as far as it was read, which the scan finds again
			}
			return , , 0, 
		}
	}
	if  == nil {
		return ,  + , , nil
	}
	if  == io.ErrUnexpectedEOF && kindOf() == KindNumber {
		 = 0 // a number which the end of the input cuts is reported at its start
	}
	return , , 0, .failAt(, +, )
}

// ReadValue returns the next raw JSON value and advances the read offset. The value has no leading and
// trailing white space, and holds the exact bytes of the input, which may contain invalid UTF-8 if
// AllowInvalidUTF8 is set.
//
// The value is only valid until the next Peek, Read or Skip call, and must not be changed while the decoder is
// used. If the next token is the end of an object or array, it reports a SyntacticError and doesn't change the
// state of the decoder. It returns io.EOF at the end of the input.
func ( *Decoder) () (Value, error) {
	 := &.d
	, ,  := .readValue()
	if  != nil {
		return nil, 
	}
	return .buf[::], nil // without the room after it, which is the input after the value
}

// SkipValue skips the next value. An object or array is read token by token, as ReadToken reads it, so that
// at an error the decoder is where the error is; another value is read as ReadValue reads it.
func ( *Decoder) () error {
	 := &.d
	if  := .PeekKind();  == KindBeginObject ||  == KindBeginArray {
		 := .st.depth()
		for {
			if ,  := .readToken();  != nil {
				return 
			}
			if .st.depth() ==  {
				return nil
			}
		}
	}
	, ,  := .readValue()
	return 
}

func ( *decoder) () (int, int, error) {
	if !.ready() {
		.setUp()
	}
	.invalidate()
	if  := .peekErr;  != nil {
		.peekErr = nil
		return 0, 0, 
	}
	,  := .beforeToken(false)
	if  != nil {
		return 0, 0, 
	}
	 := .st.last()
	switch  := .buf[]; {
	case  == '}' ||  == ']':
		// a value can't start with an end delimiter; an end delimiter which doesn't fit the innermost object or
		// array is reported as ReadToken reports it, but the end of an object which needs a value.
		if !(.needValue() &&  == '}') {
			if  := .closeError();  != nil {
				return 0, 0, 
			}
		}
		return 0, 0, .charError(, placeStartOfValue, pointNext)
	case .needName() &&  == '"':
		, , ,  := .scanToken(, pointAt)
		if  != nil {
			return 0, 0, 
		}
		if  := .insertName(, , );  != nil {
			return 0, 0, 
		}
		.count++
		.done(, )
		return , , nil
	}
	// a value where a name is must be a string, which is reported once the value is read.
	 := .needName()
	 := .count
	if .vs.final = .rerr == io.EOF; ! && (.bb != nil || .vs.final) {
		// the value is whole in the buffer, unless it is not valid: the buffer has all the input which there is.
		// From another reader, a buffer which cuts the value would be scanned twice.
		 := len(.st.names.ends)
		if ,  := .vs.scanFast(.buf, );  {
			.done(, )
			return , , nil
		}
		.st.names.truncate()
	}
	 := resumePoint{pos: , base: .st.depth()}
	 := 
	for {
		.vs.final = .rerr == io.EOF
		,  := .vs.resume(.buf, &)
		if  == nil &&  {
			.vs.restore(.base, )
			return 0, 0, .failAt(ErrNonStringName, , pointAt)
		}
		if  == nil {
			.done(, )
			return , , nil
		}
		 := false // an invalid character which the buffer cuts, read again to show it whole
		if  != errCut {
			.vs.restore(.base, )
			if ,  := .err.(*textError); ! || .rerr != nil || utf8.FullRune(.buf[.pos:]) {
				return 0, 0, &SyntacticError{ByteOffset: .base + int64(.pos), JSONPointer: .ptr, Err: .err}
			}
			// the value is read again with more input
			 = resumePoint{pos: , base: .base}
			 = true
		} else if .rerr == io.EOF {
			// the end of the input ended a number at the end of the buffer: the reader is read again for the
			// rest of the value, as encoding/json/jsontext reads it.
			.rerr = nil
		}
		for {
			,  := .fetch()
			.pos -= 
			 -= 
			if  != nil {
				// at the end of the input, the value is scanned to its end; an error of the reader is the error
				// of the value, but after an invalid character, whose error the scan finds again as far as the
				// input was read.
				if  == io.EOF ||  {
					break
				}
				 := .cutError(&, )
				.vs.restore(.base, )
				return 0, 0, 
			}
			if .tok == 0 && .pos+1 == len(.buf) && isSpace(.buf[.pos]) {
				.pos++ // a byte of white space, as a slow reader gives them, without a call
				continue
			}
			if !.stillCut(&) {
				break
			}
		}
	}
}

// cutError is the error of the reader, err, in a value which the buffer cuts at rp: where the levels which the
// value opened have a pointer, it is shown there, where the value ends as the end of the input would be: at the
// start of a number which is cut, and after the part of a literal.
func ( *decoder) ( *resumePoint,  error) error {
	if len(.st.pointerBytes(int(.where), .base)) == 0 {
		return 
	}
	 := .pos + .tok
	if .pos < len(.buf) { // a token which is cut
		switch kindOf(.buf[.pos]) {
		case KindNumber:
			 = .pos
		case KindNull, KindTrue, KindFalse:
			 = .pos + .lit
		}
	}
	return &SyntacticError{ByteOffset: .base + int64(), JSONPointer: .st.pointer(int(.where)), Err: }
}

// stillCut reads the input which a fetch added to a value which the buffer cut, and reports whether the value is
// still cut at the end of the buffer: the white space, strings and numbers which a slow reader gives a byte at a
// time are read here, without going through the states of the scanner.
func ( *decoder) ( *resumePoint) bool {
	 := .buf
	if .tok == 0 {
		.pos = skipSpace(, .pos)
		return .pos == len()
	}
	// a string or a number, which a cut token is
	if [.pos] == '"' {
		if  := plainEnd(, .pos+.tok);  == len() {
			.tok =  - .pos // plain characters continue the string, which costs one call
			return true
		}
		, ,  := scanStringFrom([.pos:], .tok, .str, strModeOf(.vs.validUTF8, true))
		if  == io.ErrUnexpectedEOF {
			.tok, .str = , 
			return true
		}
		return false
	}
	, ,  := scanNumberFrom([.pos:], .tok, .num)
	if .pos+ == len() && ( == nil ||  == io.ErrUnexpectedEOF) {
		.tok, .num = , 
		return true
	}
	return false
}

// InputOffset returns the offset in the input after the last token or value which was read. The decoder may
// have read more of the input into its buffer.
func ( *Decoder) () int64 {
	return .d.base + int64(.d.pos)
}

// UnreadBuffer returns the input in the buffer of the decoder which was read from the reader but not by
// Decoder.ReadToken or Decoder.ReadValue: it may be any number of bytes, which may not be valid JSON. How much
// input the decoder buffers may change over time.
//
// The input after the last token or value is this buffer followed by the rest of the reader.
//
// The buffer must not be changed while the decoder is used, and is valid until the next Peek, Read or Skip
// call.
func ( *Decoder) () []byte {
	return .d.buf[.d.pos:]
}

// StackDepth returns the number of the objects and arrays which are open in the input which was read: 0 at the
// top level, before any token, after a top-level value and between top-level values, 1 in a top-level object
// or array, and so on.
func ( *Decoder) () int {
	if !.d.ready() {
		.d.setUp()
	}
	return .d.st.depth() + .d.st.base // base: the levels around a decoder attached at the place of a value
}

// StackIndex returns the kind and the length of the level i of the stack, which is from 0 to
// Decoder.StackDepth: KindInvalid for the level 0, KindBeginObject for an object, KindBeginArray for an array.
// The length of an object counts its names and values: a complete object has an even length.
func ( *Decoder) ( int) (Kind, int64) {
	if !.d.ready() {
		.d.setUp()
	}
	if .d.st.outer != nil {
		return .d.st.full().index() // a decoder attached at the place of a value
	}
	return .d.st.index()
}

// StackPointer returns a JSON Pointer (RFC 6901) to the last value which was read.
func ( *Decoder) () Pointer {
	if !.d.ready() {
		.d.setUp()
	}
	return .d.st.pointer(pointLast)
}

// index is StackIndex of the stack.
func ( *stack) ( int) (Kind, int64) {
	if  > .depth() {
		_ = .levels[1:][] // the panic of encoding/json/jsontext, whose stack has the levels of the depth
	}
	 := .levels[]
	switch {
	case  == 0:
		return KindInvalid, .count
	case .object:
		return KindBeginObject, .count
	}
	return KindBeginArray, .count
}