package jsontext

import (
	
	
	
	
	
	
	

	
	
)

// valueScanner reads a JSON value, and writes it formatted if write is set. The levels of the value are pushed
// on the stack of the encoder or decoder while the value is read, so that the pointers of the errors are the
// ones of the stream.
//
// A decoder which reads its input by parts scans a value which the end of its buffer cuts up to there, and
// continues the scan from a resumePoint after it read more.
type valueScanner struct {
	st *stack
	// the options
	validUTF8            bool
	rejectDuplicateNames bool
	// lazyNames is set where the names of the objects aren't checked and the input, in, is the whole value: an
	// object keeps the position of its last name in the input, as -2 minus it in level.last, and the names are
	// added to the stack at an error only, for its pointer.
	lazyNames bool
	// base is the depth of the stack before the value being scanned, whose levels are the ones of the value after
	// it ( see addNames ).
	base     int
	in       []byte
	decoding bool // the messages and the offsets of the errors of a decoder
	final    bool // the end of the input is the end of the buffer
	// numEnd is 1 plus the end of the buffer, where the end of the input ended a number in the current resume of
	// a decoder, or 0: as encoding/json/jsontext, the decoder reads again for the rest of the value.
	numEnd int

	// the output, when the value is written
	write     bool
	out       []byte
	ws        whitespace
	esc       escapeFlags
	preserve  bool
	canonInts bool
	canonFlts bool
	reorder   bool

	run           int    // the start of the input which is not appended to out yet, which out has as it is
	spaced        bool   // the output has white space, which is compared with the input
	wsFrom, wsEnd int    // the white space of the input which skipSpace left pending
	lines         []byte // a line feed, the prefix and the indentation of the deepest line so far

	ro      reorderer // the members of the objects which are reordered, by level
	scratch []byte
	// open, if it is set, keeps the open objects of scanObjects, which scanFast otherwise keeps in its frame: a
	// scanner which is used again, as the ones of the functions of values are, doesn't clear them at every value.
	open *[64]openObject

	// the single spaces which scanObjects dropped from a written value and didn't append the run before yet: the
	// output is appended by them when the scan ends, without a call at each one
	ngaps int
	gaps  [32]int32 // the positions, which scanObjects takes for buffers below 2 GiB

	// keep is set by the functions which format a value: a written value whose output is all of its input, which
	// no part of the scan appended yet, isn't appended at its end, and kept reports it.
	keep, kept bool
}

// The places in a value where a scan continues.
const (
	atValue  uint8 = iota
	atNext         // after a value: a comma or an end delimiter
	atName         // an object name
	atColon        // the colon after an object name
	atOpened       // after a begin delimiter: a value, or the end delimiter
)

// resumePoint is where a scan which the end of the buffer cut continues: the place, and the progress in a
// string or number which was cut.
type resumePoint struct {
	at    uint8
	where uint8 // where the pointer of an error at the cut points
	pos   int   // the start of the token which was cut, or the position of the place
	tok   int   // the length of the part of the token which was taken, 0 if none
	lit   int   // the length of the part of a literal which the buffer cuts, for the position of an error there
	str   strFlags
	num   numState
	base  int // the depth of the stack before the value
}

// scanError is an error of the value at an offset, with the pointer where it was found.
type scanError struct {
	err error
	pos int
	ptr Pointer
}

func ( *valueScanner) ( error,  int,  int) *scanError {
	if .lazyNames {
		.addNames()
	}
	return &scanError{err: , pos: , ptr: .st.pointer()}
}

// addNames adds the names which the objects of the value have as their positions in the input, outer objects
// first, for the pointer of an error: not of the levels around the value, whose names are the stack's own or, at
// the level an attached coder is in, of the coder around it.
func ( *valueScanner) () {
	 := &.st.names
	for  := .base + 1;  < len(.st.levels); ++ {
		 := &.st.levels[]
		if !.object || .last >= 0 {
			continue
		}
		.first = len(.ends) // after the names added to the objects around it
		if .last < -1 {
			 := -2 - .last
			, ,  := scanString(.in[:], strModeOf(.validUTF8, false))
			.last = .first
			.add(.first, unquotedName(&.scratch, .in[:+], ))
		}
	}
}

// errCut reports a scan which the end of the buffer cut, which continues from the resume point.
var errCut = &scanError{err: io.ErrUnexpectedEOF}

// scan reads the value at b[i:], and returns the position after it, and counts it in the innermost level of the
// stack. At an error, the stack is left as it was.
func ( *valueScanner) ( []byte,  int) (int, *scanError) {
	.run, .wsEnd, .in, .kept, .base = , -1, , false, .st.depth()
	if .plain() {
		,  := len(.out), len(.st.names.ends)
		var  int
		var  bool
		if .open != nil {
			,  = .scanObjects(, , .open)
		} else {
			,  = .scanFast(, )
		}
		if  {
			.in = nil
			if .write {
				.finish(, , )
			}
			return , nil
		}
		.out, .run, .ngaps = .out[:], , 0
		.st.names.truncate()
	}
	 := .st.last().count
	 := resumePoint{pos: , base: .st.depth()}
	,  := .resume(, &)
	.in = nil
	if  != nil {
		.restore(.base, )
	} else if .write {
		.finish(, , )
	}
	return , 
}

// finish appends the rest of the output of the written value b[i:end], or, if keep is set and the output is all of
// b, which the scan didn't append any part of, leaves it out and sets kept.
func ( *valueScanner) ( []byte, ,  int) {
	if .ngaps > 0 {
		.flushGaps()
	} else if .keep && .run ==  &&  == 0 &&  == len() {
		.kept = true
		return
	}
	.flush(, )
}

// plain reports whether scanFast may read a value: its output, if it is written, is the input without white
// space, whose strings and numbers are kept as they are unless they are not canonical.
func ( *valueScanner) () bool {
	return !.spaced && !.reorder && !.canonInts && !.canonFlts && .esc == 0
}

// scanFast reads the value at b[i:] as resume does, in one loop which keeps the open objects and arrays as the
// bits of a word, without the levels of the stack or a resume point. It gives up, and reports false, where the
// value is not valid, where a string must be rewritten, deeper than 64 levels, and where the buffer may cut
// the value: resume reads it again from the start, and reports the errors. The names of the objects are checked
// as resume checks them.
func ( *valueScanner) ( []byte,  int) (int, bool) {
	if  < len() && [] != '{' && [] != '[' && [] > ' ' {
		// a string, a number or a literal, which opens no object: without the array of the open objects, which
		// would be cleared for it.
		return .scanObjects(, , nil)
	}
	// the open objects are in this frame, not in the one of scanObjects: the spilled registers of the loop are
	// then near its stack pointer, where the CPUs of AMD Zen 4 read them without a stall.
	var  [64]openObject
	return .scanObjects(, , &)
}

// openObject is an open object of valueScanner.scanFast: the index in names.ends of its first name, and the
// bits of its names ( jsonstring.NameBit ).
type openObject struct {
	first int
	bits  uint64
}

// scanObjects is scanFast, which keeps the open objects in open by their depth in the value.
//
//nolint:maintidx // one loop of gotos over the grammar, whose tokens are read in it without calls
func ( *valueScanner) ( []byte,  int,  *[64]openObject) (int, bool) {
	if len() > math.MaxInt32 {
		return , false // resume reads a buffer whose positions don't fit the gaps
	}
	var  uint64 // the bit of each open level which is an object, the innermost the lowest
	 := .ngaps   // the single spaces in gaps, in a register while the value is scanned
	var  bool
	 := 0
	 := &.st.names
	 := min(64, maxDepth-.st.depth()-.st.base) // the levels which the value may open
	 := strModeOf(.validUTF8, false)
	var  int
	var  strFlags
	var  error

:
	if  < len() && [] <= ' ' {
		goto 
	}
:
	if  == len() {
		return , false
	}
	switch  := [];  {
	case '{', '[':
		if  ==  {
			return , false
		}
		 <<= 1
		if  == '{' {
			 |= 1
			[] = openObject{first: len(.ends)}
		}
		++
		++
		goto 
	case '"':
		// a string of plain characters costs one call; scanStringFrom takes the others from where it stops
		if  = plainEnd(, +1) - ; + < len() && [+] == '"' {
			++
		} else if , ,  = scanStringFrom([:], , 0, );  != nil || .write && &strNonCanonical != 0 && !.preserve {
			return , false
		}
		 += 
	case 'n':
		// the literals are compared in the loop, without a call
		if len()- < 4 || string([:+4]) != "null" {
			return , false
		}
		 += 4
	case 't':
		if len()- < 4 || string([:+4]) != "true" {
			return , false
		}
		 += 4
	case 'f':
		if len()- < 5 || string([:+5]) != "false" {
			return , false
		}
		 += 5
	default:
		// a number of the common forms, an integer and its fraction, is read in the loop: the digits of the
		// integer by bytes, and the ones of the fraction 8 bytes at a time. numberEnd reads the others. A number
		// which the buffer ends may continue after it.
		 := 
		if  == '-' {
			++
		}
		if  < len() && '1' <= [] && [] <= '9' {
			for ++;  < len() && '0' <= [] && [] <= '9'; {
				++
			}
		} else if  < len() && [] == '0' {
			++
		} else {
			 = 
		}
		if  >  && +1 < len() && [] == '.' && '0' <= [+1] && [+1] <= '9' {
			 = jsonnum.ScanDigits(, +2)
		}
		if  >  &&  < len() && [] != '.' && [] != 'e' && [] != 'E' {
			 = 
		} else if  = jsonnum.End([:]);  < 0 {
			return , false
		} else {
			 += 
		}
	}

:
	if  == 0 {
		.st.last().count++
		.ngaps = 
		return , true
	}
	if  < len() && [] <= ' ' {
		goto 
	}
:
	if  == len() {
		return , false
	}
	switch  := []; {
	case  == ',':
		++
		if &1 != 0 {
			goto 
		}
		goto 
	case  == '}' && &1 != 0,  == ']' && &1 == 0:
		++
		goto 
	}
	return , false

:
	--
	if &1 != 0 {
		.truncate([].first)
	}
	 >>= 1
	goto 

:
	if  < len() && [] <= ' ' {
		goto 
	}
:
	if  == len() {
		return , false
	}
	if  := [];  == '}' && &1 != 0 ||  == ']' && &1 == 0 {
		++
		goto 
	}
	if &1 != 0 {
		goto 
	}
	goto 

:
	if  < len() && [] <= ' ' {
		goto 
	}
:
	if  == len() || [] != '"' {
		return , false
	}
	 = 0
	if  = plainEnd(, +1) - ; + < len() && [+] == '"' {
		++
	} else if , ,  = scanStringFrom([:], , 0, );  != nil || .write && &strNonCanonical != 0 && !.preserve {
		return , false
	}
	if .rejectDuplicateNames {
		 := [+1 : +-1] // a name without escape sequences is the bytes between its quotes, without a call
		if &(strEscaped|strInvalidUTF8) != 0 {
			 = unquotedName(&.scratch, [:+], )
		}
		 :=  - 1
		 := &[]
		if  := jsonstring.NameBit(); .bits& == 0 {
			.bits |= 
		} else if .has(.first, ) {
			return , false
		}
		.add(.first, )
	}
	 += 
	if  < len() && [] <= ' ' {
		goto 
	}
:
	if  == len() || [] != ':' {
		return , false
	}
	++
	goto 

	// the white space before the tokens, which the loop jumps out to, so that it doesn't lie between them
:
	if ,  = .oneSpace(, , );  {
		++
	} else {
		.ngaps = 
		 = .skipSpace(, )
		 = .ngaps
	}
	goto 
:
	if ,  = .oneSpace(, , );  {
		++
	} else {
		.ngaps = 
		 = .skipSpace(, )
		 = .ngaps
	}
	goto 
:
	if ,  = .oneSpace(, , );  {
		++
	} else {
		.ngaps = 
		 = .skipSpace(, )
		 = .ngaps
	}
	goto 
:
	if ,  = .oneSpace(, , );  {
		++
	} else {
		.ngaps = 
		 = .skipSpace(, )
		 = .ngaps
	}
	goto 
:
	if ,  = .oneSpace(, , );  {
		++
	} else {
		.ngaps = 
		 = .skipSpace(, )
		 = .ngaps
	}
	goto 
}

// restore pops the levels of a value which was not read to its end.
func ( *valueScanner) ( int,  int64) {
	for .st.depth() >  {
		.st.pop()
	}
	.st.last().count = 
	.ro.reset()
}

// resume scans the value from the resume point. If the end of the buffer cuts it and the input continues, it
// returns errCut, with the resume point where the scan continues.
//
//nolint:maintidx // one loop of gotos over the grammar, whose state stays in its variables
func ( *valueScanner) ( []byte,  *resumePoint) (int, *scanError) {
	var  error
	var  int
	 := .pos
	 := .base
	.numEnd = 0
	 := wsNone     // the white space which a written value has before the next token
	 := .st.last() // the innermost level, which a push and a close change
	switch .at {
	case atNext:
		goto 
	case atName:
		goto 
	case atColon:
		goto 
	case atOpened:
		goto 
	}

:
	if  = .skip(, );  == len() {
		if .st.depth() ==  {
			return .cut(atValue, , pointNext, ) // an empty value, which the encoder counts as the next one
		}
		return .cut(atValue, , pointAt, )
	}
	if .spaced {
		.space(, , )
	}
	switch  := [];  {
	case '{', '[':
		if  := .st.push( == '{');  != nil {
			return , .fail(, , pointNext)
		}
		 = .st.last()
		if .write &&  == '{' && .reorder {
			.flush(, +1)
			.ro.open(len(.out))
		}
		++
		goto 
	case '"':
		var  strFlags
		if .tok > 0 && !.final && plainEnd(, +.tok) == len() {
			// plain characters continue the string to the end of the buffer, as a slow reader gives them
			.tok = len() - 
			return .cut(atValue, , pointNext, )
		} else if .tok > 0 {
			, ,  = scanStringFrom([:], .tok, .str, strModeOf(.validUTF8, !.final))
			.tok = 0
		} else if  = plainEnd(, +1) - ; + < len() && [+] == '"' {
			++ // a string of plain characters costs one call
		} else {
			, ,  = scanStringFrom([:], , 0, strModeOf(.validUTF8, !.final))
		}
		if  != nil {
			if  == io.ErrUnexpectedEOF && !.final {
				.tok, .str = , 
				return .cut(atValue, , pointNext, )
			}
			return  + , .fail(, +, pointNext)
		}
		if .write {
			.writeString(, , , )
		}
		 += 
	case 'n', 't', 'f':
		 := literalOf(Kind())
		,  = scanLiteral([:], )
		if  != nil {
			if  == io.ErrUnexpectedEOF && !.final {
				.lit = 
				return .cut(atValue, , pointNext, )
			}
			return  + , .fail(, +, pointNext)
		}
		 += 
	default:
		if kindOf() != KindNumber {
			if  := &.st.levels[]; .decoding &&  > 0 && .count > 1 && ( == ']' && .object ||  == '}' && !.object) {
				// encoding/json/jsontext reports an end delimiter where a value is, in a value which a decoder
				// reads in an object or array, as the error of the object or array where the value is, when it
				// is the end of the other kind.
				if .object {
					return , .fail(invalidChar([:], placeAfterObjectValue), , pointHere)
				}
				return , .fail(invalidChar([:], placeAfterArrayElement), , pointHere)
			}
			return , .fail(invalidChar([:], placeStartOfValue), , pointNext)
		}
		var  numState
		if .tok > 0 {
			, ,  = scanNumberFrom([:], .tok, .num)
			.tok = 0
		} else {
			// a number of the common forms is read here as scanObjects reads it, and the others by numberEnd
			 := 
			if  == '-' {
				++
			}
			if  < len() && '1' <= [] && [] <= '9' {
				for ++;  < len() && '0' <= [] && [] <= '9'; {
					++
				}
			} else if  < len() && [] == '0' {
				++
			} else {
				 = 
			}
			if  >  && +1 < len() && [] == '.' && '0' <= [+1] && [+1] <= '9' {
				 = jsonnum.ScanDigits(, +2)
			}
			if  >  &&  < len() && [] != '.' && [] != 'e' && [] != 'E' {
				 =  - 
			} else if  = jsonnum.End([:]);  < 0 {
				, ,  = scanNumberFrom([:], 0, numState{})
			}
		}
		if + == len() && ( == nil ||  == io.ErrUnexpectedEOF) {
			if !.final {
				.tok, .num = , 
				return .cut(atValue, , pointNext, )
			}
			if  == nil && .decoding {
				.numEnd = len() + 1
			}
		}
		if  != nil {
			// a decoder reports a number which the input cuts at its start.
			if  != io.ErrUnexpectedEOF {
				// the position of the invalid character
			} else if .decoding {
				 = 0
			} else {
				 = .done
			}
			return  + , .fail(, +, pointNext)
		}
		if .write && !.numberKept([:+]) {
			.flush(, )
			.out = appendCanonicalNumber(.out, [:+])
			.run =  + 
		}
		 += 
	}
	.count++

:
	if .st.depth() ==  {
		return , nil
	}
	if  = .skip(, );  == len() {
		return .cut(atNext, , pointAt, )
	}
	if .object {
		switch [] {
		case ',':
			if .spaced && .wsEnd ==  {
				.space(, , wsNone)
			}
			if .write && .reorder {
				.flush(, )
				.ro.endMember(len(.out))
			}
			++
			 = wsElem
			goto 
		case '}':
			.closeLevel(, , false)
			 = .st.last()
			++
			goto 
		}
		return , .fail(invalidChar([:], placeAfterObjectValue), , pointAt)
	}
	switch [] {
	case ',':
		if .spaced && .wsEnd ==  {
			.space(, , wsNone)
		}
		++
		 = wsElem
		goto 
	case ']':
		.closeLevel(, , false)
		 = .st.last()
		++
		goto 
	}
	if .decoding {
		return , .fail(invalidChar([:], placeAfterArrayElement), , pointAt)
	}
	return , .fail(invalidChar([:], placeAfterArrayValue), , pointAt)

:
	if  = .skip(, );  == len() {
		return .cut(atOpened, , pointAt, )
	}
	if [] == '}' && .object || [] == ']' && !.object {
		.closeLevel(, , true)
		 = .st.last()
		++
		goto 
	} else if  = wsOpen; .object {
		goto 
	}
	goto 

:
	if  = .skip(, );  == len() {
		return .cut(atName, , pointAt, )
	}
	if .spaced {
		.space(, , )
	}
	if [] != '"' {
		return , .fail(invalidChar([:], placeStartOfString), , pointAt)
	}
	{
		var  strFlags
		if .tok > 0 && !.final && plainEnd(, +.tok) == len() {
			// plain characters continue the string to the end of the buffer, as a slow reader gives them
			.tok = len() - 
			return .cut(atName, , pointAt, )
		} else if .tok > 0 {
			, ,  = scanStringFrom([:], .tok, .str, strModeOf(.validUTF8, !.final))
			.tok = 0
		} else if  = plainEnd(, +1) - ; + < len() && [+] == '"' {
			++ // a string of plain characters costs one call
		} else {
			, ,  = scanStringFrom([:], , 0, strModeOf(.validUTF8, !.final))
		}
		if  != nil {
			if  == io.ErrUnexpectedEOF && !.final {
				.tok, .str = , 
				return .cut(atName, , pointAt, )
			}
			return  + , .fail(, +, pointAt)
		}
		 := [ : +]
		if .lazyNames {
			.last, .named = -2-, .count+1
		} else {
			 := [1 : len()-1] // a name without escape sequences, without a call
			if &(strEscaped|strInvalidUTF8) != 0 {
				 = unquotedName(&.scratch, , )
			}
			if !.st.insertName(, .rejectDuplicateNames) {
				return , &scanError{err: ErrDuplicateName, pos: , ptr: .st.namePointer()}
			}
		}
		.count++
		if .write {
			if .reorder {
				.flush(, )
				.ro.startMember(len(.out), unquotedName(&.scratch, , ))
			}
			.writeString(, , , )
		}
		 += 
	}

:
	if  = .skip(, );  == len() {
		return .cut(atColon, , pointAt, )
	}
	if [] != ':' {
		return , .fail(invalidChar([:], placeAfterObjectName), , pointAt)
	}
	if .spaced && .wsEnd ==  {
		.space(, , wsNone)
	}
	++
	 = wsColon
	goto 
}

// cut is the end of the scan at the end of the buffer, at the place at, where the token or the place starts at
// i: the input continues, or the value is not complete.
func ( *valueScanner) ( uint8,  int,  int,  *resumePoint) (int, *scanError) {
	if .final && +1 != .numEnd {
		 :=  + .tok
		if .tok == 0 {
			 = 
		}
		return , .fail(io.ErrUnexpectedEOF, , )
	}
	.at, .pos, .where = , , uint8()
	return , errCut
}

// The output is the input where they are the same: the run of the input from s.run, which is not appended yet,
// is appended where the output differs, before what the output has instead.

// flush appends the run of the input up to i.
func ( *valueScanner) ( []byte,  int) {
	if .run <  {
		.out = append(.out, [.run:]...)
	}
	.run = 
}

// flushGaps appends the runs of the input before the single spaces which scanObjects dropped, short ones by a word.
func ( *valueScanner) ( []byte) {
	,  := .out, .run // in registers, not in the scanner, while the runs are appended
	for ,  := range .gaps[:.ngaps] {
		 := int()
		if  :=  - ;  <= 8 && +8 <= len() && cap()-len() >= 8 {
			 := len()
			binary.LittleEndian.PutUint64([:+8], binary.LittleEndian.Uint64([:]))
			 = [:+]
		} else {
			 = append(, [:]...)
		}
		 =  + 1
	}
	.out, .run, .ngaps = , , 0
}

// oneSpace reports whether b[i] is a single space before a token, the most common white space, which scanObjects
// skips without a call: a written value keeps it in gaps, and so does one which isn't, without counting it, as
// long as there is room. k is the number of the gaps, which scanObjects keeps in a register while it scans, and
// it returns the new one. It is inlined.
func ( *valueScanner) ( []byte, ,  int) (int, bool) {
	if  < len(.gaps) && +1 < len() && [] == ' ' && [+1] > ' ' {
		.gaps[] = int32()
		return  + int(bit(.write)), true
	}
	return , false
}

// bit is 1 for true and 0 for false.
func bit( bool) uint64 {
	if  {
		return 1
	}
	return 0
}

// skip skips the white space at b[i:], which a written value doesn't have. It is inlined where there is none.
func ( *valueScanner) ( []byte,  int) int {
	if  < len() && [] <= ' ' {
		return .skipSpace(, )
	}
	return 
}

// skipSpace skips the white space at b[i:]. A value written without white space drops it; one written with white
// space keeps it pending, for space to compare with the white space which the output has there.
func ( *valueScanner) ( []byte,  int) int {
	// the loop of skipSpace, which is not called: it runs at every token of a value with white space
	 := 
	for  < len() && isSpace([]) {
		++
		if [-1] == '\n' &&  < len() && ([] == ' ' || [] == '\t') {
			 = skipIndent(, )
		}
	}
	switch {
	case !.write:
	case .spaced:
		.wsFrom, .wsEnd = , 
	default:
		if .ngaps > 0 {
			.flushGaps()
		}
		// a short run, as a token between spaces is, is copied by a word without a call of memmove.
		if  :=  - .run;  <= 8 && .run+8 <= len() && cap(.out)-len(.out) >= 8 {
			 := len(.out)
			binary.LittleEndian.PutUint64(.out[:+8], binary.LittleEndian.Uint64([.run:]))
			.out = .out[:+]
		} else {
			.flush(, )
		}
		.run = 
	}
	return 
}

// The white space which a value written with white space has before a token.
const (
	wsNone  = iota // none
	wsColon        // after a colon
	wsElem         // before an element or a member after the first one, after its comma
	wsOpen         // before the first element or member
	wsClose        // before the end of an object or array which is not empty
)

// space writes the white space of the kind ws before the token at b[i]: the white space of the input before it,
// which skipSpace left pending, is kept if it is the same.
func ( *valueScanner) ( []byte,  int,  int) {
	 := 
	if .wsEnd ==  {
		 = .wsFrom
	}
	.wsEnd = -1 // the pending white space is taken

	var  bool
	var  []byte
	switch  {
	case wsColon:
		 = .ws.colon
	case wsElem, wsOpen, wsClose:
		 =  == wsElem && .ws.comma
		if .ws.multiline {
			 := .st.depth()
			if  == wsClose {
				--
			}
			 = .line()
		}
	}
	 := [:]
	 := true
	if  {
		 = len() > 0 && [0] == ' '
		if  {
			 = [1:]
		}
	}
	if ! || string() != string() {
		.flush(, )
		if  {
			.out = append(.out, ' ')
		}
		.out = append(.out, ...)
		.run = 
	}
}

// line returns a line feed, the prefix and the indentation of the depth, sliced from a buffer which holds the
// deepest line so far.
func ( *valueScanner) ( int) []byte {
	if len(.lines) == 0 {
		.lines = append(append(.lines, '\n'), .ws.prefix...)
	}
	 := 1 + len(.ws.prefix) + *len(.ws.indent)
	for len(.lines) <  {
		.lines = append(.lines, .ws.indent...)
	}
	return .lines[:]
}

// writeString writes the string b[i:i+n], which scanString took with the flags f. It is inlined where the
// string is written as it is, without the options which escape more.
func ( *valueScanner) ( []byte, ,  int,  strFlags) {
	if &strNonCanonical != 0 && !.preserve || .esc != 0 {
		.rewriteString(, , , )
	}
}

func ( *valueScanner) ( []byte, ,  int,  strFlags) {
	if !rawStringKept([:+], , .esc, .preserve) {
		.flush(, )
		.out = appendRawString(.out, [:+], , .esc, .preserve)
		.run =  + 
	}
}

// closeLevel pops the innermost object or array, whose end delimiter is at b[i].
func ( *valueScanner) ( []byte,  int,  bool) {
	if .write {
		if [] == '}' && .reorder {
			// the members end before the white space which is pending
			 := 
			if .spaced && .wsEnd ==  {
				 = .wsFrom
			}
			.flush(, )
			.ro.endMember(len(.out))
			.out = .ro.close(.out)
		}
		if .spaced {
			if  {
				if .wsEnd ==  {
					.space(, , wsNone)
				}
			} else {
				.space(, , wsClose)
			}
		}
	}
	.st.pop()
}

// appendComma appends a comma, and the space after it if the options want it.
func ( *whitespace) ( []byte) []byte {
	if .comma {
		return append(, ',', ' ')
	}
	return append(, ',')
}

// appendLine appends a line feed, the prefix and the indentation of the depth.
func ( *whitespace) ( []byte,  int) []byte {
	 = append(, '\n')
	 = append(, .prefix...)
	for range  {
		 = append(, .indent...)
	}
	return 
}

// numberKept reports whether the options keep the number b as it is. -0 is 0 under either option, and an
// integer of at most 15 digits is exact as a double, which is formatted by its digits.
func ( *valueScanner) ( []byte) bool {
	if !.canonInts && !.canonFlts {
		return true
	}
	if string() == "-0" {
		return false
	}
	if isInteger() {
		return !.canonInts || len() <= 15
	}
	return !.canonFlts
}

// reorderer holds the members of the objects which ReorderRawObjects reorders, the innermost object last: the
// output of each member, from the start of its name to the end of its value, and its unquoted name. Its arrays
// are used again by the objects after.
type reorderer struct {
	objects []object // the open objects
	members []member // their members, back to back
	names   []byte   // the names of the members, back to back
	sorted  []member
	buf     []byte
}

type object struct {
	start   int // the start of the output of its members
	members int // the index of its first member
}

type member struct {
	name, nameEnd int // the name, in names
	start, end    int // the output
}

func ( *reorderer) () {
	.objects, .members, .names = .objects[:0], .members[:0], .names[:0]
}

func ( *reorderer) ( int) {
	.objects = append(.objects, object{start: , members: len(.members)})
}

func ( *reorderer) ( int,  []byte) {
	.names = append(.names, ...)
	.members = append(.members, member{name: len(.names) - len(), nameEnd: len(.names), start: , end: -1})
}

func ( *reorderer) ( int) {
	if  := len(.members);  > .objects[len(.objects)-1].members && .members[-1].end < 0 {
		.members[-1].end = 
	}
}

// close sorts the members of the innermost object in out, which are separated by commas and white space, by
// their names, and drops the object.
func ( *reorderer) ( []byte) []byte {
	 := .objects[len(.objects)-1]
	 := .members[.members:]
	defer func() {
		.objects = .objects[:len(.objects)-1]
		if len() > 0 {
			.names = .names[:[0].name]
		}
		.members = .members[:.members]
	}()
	// members of the same name are ordered by their output, from the name on, in the same order.
	 := func(,  member) int {
		if  := compareNames(.names[.name:.nameEnd], .names[.name:.nameEnd]);  != 0 {
			return 
		}
		return compareNames(bytes.TrimLeft([.start:.end], ", \n\r\t"), bytes.TrimLeft([.start:.end], ", \n\r\t"))
	}
	if len() < 2 || slices.IsSortedFunc(, ) {
		return 
	}
	.sorted = append(.sorted[:0], ...)
	slices.SortFunc(.sorted, )
	// the separator of the members, from the end of the first one to the start of the second one.
	 := [[0].end:[1].start]
	 := append(.buf[:0], [.start:[0].start]...)
	for ,  := range .sorted {
		if  > 0 {
			 = append(, ...)
		}
		 = append(, [.start:.end]...)
	}
	 = append(, [[len()-1].end:]...)
	.buf = 
	return append([:.start], ...)
}

// compareNames orders names by their UTF-16 code units, as RFC 8785, section 3.2.3 does. A byte of invalid UTF-8
// is U+FFFD, which is ordered by its bytes where the other is U+FFFD too, as encoding/json/jsontext orders it.
func compareNames(,  []byte) int {
	for len() > 0 && len() > 0 {
		,  := utf8.DecodeRune()
		,  := utf8.DecodeRune()
		if  !=  {
			,  := utf16Units(), utf16Units()
			if [0] != [0] {
				return int([0]) - int([0])
			}
			return int([1]) - int([1])
		}
		if  == utf8.RuneError && ( == 1 ||  == 1) && [0] != [0] {
			return int([0]) - int([0])
		}
		,  = [:], [:]
	}
	return len() - len()
}

// utf16Units are the UTF-16 code units of r, the second one 0 if it has one.
func utf16Units( rune) [2]uint16 {
	if ,  := utf16.EncodeRune();  != utf8.RuneError {
		return [2]uint16{uint16(), uint16()}
	}
	return [2]uint16{uint16(), 0}
}