package jsontext

import (
	
	
	
	
	
	
	

	
	
	
)

// The scanners of the text of a token take the text from its first byte, and return the number of bytes which
// they took and an error. At an error, the number is the position of the error in the text: the character which
// is invalid, or, at the end of the text, the end of what is complete.

// isSpace reports whether c is JSON white space.
func isSpace( byte) bool {
	return  == ' ' ||  == '\t' ||  == '\r' ||  == '\n'
}

// skipWS is skipSpace, which it calls only where b[i] is white space: it is inlined, so that a token without
// white space before it costs no call.
func skipWS( []byte,  int) int {
	if  < len() && [] <= ' ' {
		return skipSpace(, )
	}
	return 
}

// skipSpace returns the position of the first byte of b from i which is not white space, or len(b). The
// indentation after a line feed is taken 8 spaces or 8 tabs at a time.
func skipSpace( []byte,  int) int {
	for  < len() {
		 := []
		if  > ' ' || !isSpace() {
			break
		}
		++
		if  == '\n' &&  < len() && ([] == ' ' || [] == '\t') {
			 = skipIndent(, )
		}
	}
	return 
}

// skipIndent returns the end of the run of the byte at b[i], a space or a tab, as the indentation of a line has
// it, looked at 8 bytes at a time.
func skipIndent( []byte,  int) int {
	 := uint64([]) * 0x0101010101010101
	for +8 <= len() {
		// the bytes of the run are 0 in x, and the first one which is not is its lowest byte which is not.
		if  := binary.LittleEndian.Uint64([:]) ^ ;  != 0 {
			return  + bits.TrailingZeros64()/8
		}
		 += 8
	}
	return 
}

// scanLiteral takes the literal lit ( null, true or false ) at the start of b.
func scanLiteral( []byte,  string) (int, error) {
	// the comparisons with constants, which are words, not calls
	switch {
	case len() >= 4 && ( == "null" && string([:4]) == "null" ||  == "true" && string([:4]) == "true"):
		return 4, nil
	case len() >= 5 &&  == "false" && string([:5]) == "false":
		return 5, nil
	}
	for  := 0;  < len(); ++ {
		if  == len() {
			return , io.ErrUnexpectedEOF
		}
		if [] != [] {
			return , invalidLiteralChar([:], , )
		}
	}
	return len(), nil
}

// literalOf is the literal of kind k.
func literalOf( Kind) string {
	switch  {
	case KindNull:
		return "null"
	case KindTrue:
		return "true"
	}
	return "false"
}

// numState is the progress of a scan of a JSON number: what comes next, and the end of the longest complete
// number which was taken.
type numState struct {
	next numPart
	done int
}

type numPart uint8

const (
	numSign     numPart = iota // a minus sign or the first digit
	numFirst                   // the first digit
	numInt                     // the digits of the integer after the first one, which is not 0
	numAfterInt                // a fraction, an exponent or the end
	numDot                     // the first digit of the fraction
	numFrac                    // the digits of the fraction after the first one
	numAfterFrc                // an exponent or the end
	numE                       // the sign of the exponent or its first digit
	numExpFirst                // the first digit of the exponent
	numExp                     // the digits of the exponent after the first one
)

// scanNumber takes the JSON number at the start of b. At an error, the number is the position of the invalid
// character, or, if b ends before the number is complete, the end of the longest complete number which b
// starts with, with io.ErrUnexpectedEOF. A number which may continue after the end of b is returned without an
// error: a caller which may read more input continues it by scanNumberFrom.
func scanNumber( []byte) (int, error) {
	, ,  := scanNumberFrom(, 0, numState{})
	if  == io.ErrUnexpectedEOF {
		 = .done
	}
	return , 
}

// inDigits reports whether the number is in a run of digits, which more digits continue without a change of state.
func ( numState) () bool {
	return .next == numInt || .next == numFrac || .next == numExp
}

// scanNumberFrom continues the scan of the number which starts b at b[i:], where st was.
func scanNumberFrom( []byte,  int,  numState) (int, numState, error) {
	// the digits which continue a run of digits to the end of b, as a slow reader gives them, change no state
	if .inDigits() {
		if  = jsonnum.ScanDigits(, );  == len() {
			.done = 
			return , , nil
		}
	}
	for {
		if  == len() {
			switch .next {
			case numSign, numFirst, numDot, numE, numExpFirst:
				return , , io.ErrUnexpectedEOF
			}
			return , , nil
		}
		 := []
		switch .next {
		case numSign:
			.next = numFirst
			if  == '-' {
				++
			}
			continue
		case numFirst:
			if  == '0' {
				++
				.next = numAfterInt
			} else if '1' <=  &&  <= '9' {
				 = jsonnum.ScanDigits(, +1)
				.next = numInt
			} else {
				return , , invalidChar([:], placeInNumber)
			}
			.done = 
			continue
		case numInt:
			 = jsonnum.ScanDigits(, )
			.done = 
			if  == len() {
				continue
			}
			.next = numAfterInt
			continue
		case numAfterInt, numAfterFrc:
			if  == '.' && .next == numAfterInt {
				.next = numDot
			} else if  == 'e' ||  == 'E' {
				.next = numE
			} else {
				return , , nil
			}
			++
			continue
		case numDot:
			if  < '0' || '9' <  {
				return , , invalidChar([:], placeInNumber)
			}
			.next = numFrac
			++
			continue
		case numFrac:
			 = jsonnum.ScanDigits(, )
			.done = 
			if  < len() {
				.next = numAfterFrc
			}
			continue
		case numE:
			.next = numExpFirst
			if  == '+' ||  == '-' {
				++
			}
			continue
		case numExpFirst:
			if  < '0' || '9' <  {
				return , , invalidChar([:], placeInNumber)
			}
			.next = numExp
			++
			continue
		case numExp:
			 = jsonnum.ScanDigits(, )
			if  < len() {
				return , , nil
			}
			continue
		}
	}
}

// isInteger reports whether the JSON number b has no fraction and no exponent.
func isInteger( []byte) bool {
	for ,  := range  {
		if  == '.' ||  == 'e' ||  == 'E' {
			return false
		}
	}
	return true
}

// strFlags describe a JSON string.
type strFlags uint8

const (
	strEscaped      strFlags = 1 << iota // it has an escape sequence
	strNonCanonical                      // AppendQuote writes its value otherwise
	strInvalidUTF8                       // it has invalid UTF-8, or an escaped surrogate which is not in a pair
	strHighCut                           // without strValid, a high surrogate ends the buffer, which a low one may pair
)

// stringClass is the class of each byte in a JSON string: 0 for a character taken as it is, 1 for an escape
// or a byte which ends the characters, 2 for the start of a character which is not ASCII.
var stringClass = func() [256]uint8 {
	var  [256]uint8
	for  := range  {
		switch {
		case  < ' ':
			[] = 1
		case  == '"',  == '\\':
			[] = 1
		case  >= utf8.RuneSelf:
			[] = 2
		}
	}
	return 
}()

// The masks of the bytes of a word of 8 bytes, which is looked at by arithmetic on all its bytes at once. A mask
// has the top bit of each byte which is found: the first one is exact, and the ones after it may be not, as a
// borrow may spread from a byte which is found to the next one. The words are loaded in little-endian order,
// so that the first byte is the lowest one on any machine.
const (
	lsb = 0x0101010101010101
	msb = 0x8080808080808080
)

// zeroBytes has the top bit of the bytes of w which are 0.
func zeroBytes( uint64) uint64 {
	return ( - lsb) &^  & msb
}

// specialBytes has the top bit of the bytes of w which a string doesn't take as they are: a quote, a backslash,
// a control character or a byte of 0x80 or more.
func specialBytes( uint64) uint64 {
	// a byte below 0x20 borrows in w - 0x20 per byte; the top bits of w are the bytes of 0x80 or more.
	return zeroBytes(^('"'*lsb)) | zeroBytes(^('\\'*lsb)) | (-' '*lsb)&^&msb | &msb
}

// plainEnd returns the position of the first byte of b from i which is not ASCII taken as it is in a string: a
// quote, a backslash, a control character or a byte of 0x80 or more; or len(b).
func plainEnd( []byte,  int) int {
	for +8 <= len() {
		if  := specialBytes(binary.LittleEndian.Uint64([:]));  != 0 {
			return  + bits.TrailingZeros64()/8
		}
		 += 8
	}
	for  < len() && stringClass[[]] == 0 {
		++
	}
	return 
}

// simpleStringEnd returns the end of the string which starts b, which starts with a quote, if it is short and its
// characters are ASCII to take as they are, and true; or else the position from which scanStringFrom continues,
// and false. It scans the characters 8 bytes at a time, as scanStringFrom does, which then takes the rest.
func simpleStringEnd( []byte) (int, bool) {
	 := 1
	if  < len() && stringClass[[]] == 0 {
		 = plainEnd(, 2)
	}
	if  < len() && [] == '"' {
		return  + 1, true
	}
	return , false
}

// strMode is how a string is scanned.
type strMode uint8

const (
	strValid strMode = 1 << iota // invalid UTF-8 and escaped surrogates which are not in pairs are errors
	strMore                      // the input may continue after the end of the buffer
)

func strModeOf(,  bool) strMode {
	var  strMode
	if  {
		 |= strValid
	}
	if  {
		 |= strMore
	}
	return 
}

// scanString takes the JSON string at the start of b, which starts with a quote. With strValid, invalid UTF-8
// and escaped surrogates which are not in pairs are errors; else they are reported by strInvalidUTF8. If b
// ends before the string, the error is io.ErrUnexpectedEOF at the start of the character which is not
// complete, from which scanStringFrom continues when there is more input. A character which may be complete
// only with more input is taken as it is unless the mode has strMore.
func scanString( []byte,  strMode) (int, strFlags, error) {
	return scanStringFrom(, 1, 0, )
}

// scanStringFrom continues the scan of the string which starts b at b[i:], with the flags of b[:i].
func scanStringFrom( []byte,  int,  strFlags,  strMode) (int, strFlags, error) {
	if &strHighCut != 0 {
		var  bool
		if , ,  = pairHighCut(, , );  {
			return , , io.ErrUnexpectedEOF
		}
	}
	for {
		// the characters taken as they are: ASCII other than a quote, a backslash and a control character
		if  < len() && stringClass[[]] == 0 {
			 = plainEnd(, )
		}
		if  == len() {
			return , , io.ErrUnexpectedEOF
		}
		switch  := []; {
		case  == '"':
			return  + 1, , nil
		case  == '\\':
			// \uXXXX of a character which is not a surrogate, as most escape sequences are, without a call
			if +6 <= len() && [+1] == 'u' {
				if  := hex4([+2:]);  >= 0 && !utf16.IsSurrogate() {
					 |= strEscaped
					if !isCanonicalEscape([:+6], ) {
						 |= strNonCanonical
					}
					 += 6
					continue
				}
			}
			, ,  := scanEscape([:], )
			if  != nil {
				return , , 
			}
			 |= strEscaped
			if  == highCut {
				 |= strHighCut | strNonCanonical
			} else if  < 0 {
				 |= strInvalidUTF8 | strNonCanonical
			} else if !isCanonicalEscape([:+], ) {
				 |= strNonCanonical
			}
			 += 
		case  < ' ':
			return , , invalidChar([:], placeInString)
		default:
			// a run of characters which are not ASCII, and ASCII ones, validated at once, and a character at a
			// time only if it is not valid.
			 := charsEnd(, )
			if utf8.Valid([:]) {
				 = 
				continue
			}
			for  <  {
				,  := utf8.DecodeRune([:])
				if  == utf8.RuneError &&  == 1 {
					if  == len() && !utf8.FullRune([:]) {
						return , , io.ErrUnexpectedEOF
					}
					if &strValid != 0 {
						return , , errInvalidUTF8
					}
					 |= strInvalidUTF8 | strNonCanonical
				}
				 += 
			}
		}
	}
}

// charsEnd returns the position of the first byte of b from i which is a quote, a backslash or a control
// character, or len(b): the characters before it are taken as they are, once they are valid UTF-8.
func charsEnd( []byte,  int) int {
	for +8 <= len() {
		 := binary.LittleEndian.Uint64([:])
		if  := zeroBytes(^('"'*lsb)) | zeroBytes(^('\\'*lsb)) | (-' '*lsb)&^&msb;  != 0 {
			return  + bits.TrailingZeros64()/8
		}
		 += 8
	}
	for  < len() && ([] >= ' ' && [] != '"' && [] != '\\') {
		++
	}
	return 
}

// isCanonicalEscape reports whether the escape sequence e of r is the one which AppendQuote writes.
func isCanonicalEscape( []byte,  rune) bool {
	if  >= ' ' &&  != '"' &&  != '\\' {
		return false // written as it is
	}
	switch  {
	case '"', '\\', '\b', '\f', '\n', '\r', '\t':
		return len() == 2
	}
	return len() == 6 && [4] == hexDigits[>>4] && [5] == hexDigits[&0xf]
}

const hexDigits = "0123456789abcdef"

// highCut is the rune of scanEscape for a high surrogate which the end of the buffer cuts from the escape
// sequence which may pair it, without strValid: encoding/json/jsontext takes it alone, and so does the scan,
// which pairs it when it continues.
const highCut = -2

// pairHighCut takes the escape sequence at b[i:] after a high surrogate which was cut from it, as the flags tell:
// it pairs a low surrogate, else the high one is not in a pair. It reports whether b ends in it.
func pairHighCut( []byte,  int,  strFlags) (int, strFlags, bool) {
	if +6 > len() && isPrefixOfLowSurrogate([:]) {
		return , , true
	}
	 &^= strHighCut
	if +6 <= len() && [] == '\\' && [+1] == 'u' {
		if  := hex4([+2:]);  >= 0xdc00 &&  < 0xe000 {
			return  + 6, , false
		}
	}
	return ,  | strInvalidUTF8, false
}

// scanEscape takes the escape sequence at the start of b, and returns its length and the rune: -1 for an
// escaped surrogate which is not in a pair, which is an error with strValid, and highCut.
func scanEscape( []byte,  strMode) (int, rune, error) {
	if len() < 2 {
		return 0, 0, io.ErrUnexpectedEOF
	}
	switch [1] {
	case '"', '\\', '/':
		return 2, rune([1]), nil
	case 'b':
		return 2, '\b', nil
	case 'f':
		return 2, '\f', nil
	case 'n':
		return 2, '\n', nil
	case 'r':
		return 2, '\r', nil
	case 't':
		return 2, '\t', nil
	case 'u':
		// a cut escape sequence waits for more input while its bytes may still be valid: scanHex4 reports the
		// error of a byte which is not a digit at once, as encoding/json/jsontext does.
		,  := scanHex4()
		if  != nil {
			return 0, 0, 
		}
		if !utf16.IsSurrogate() {
			return 6, , nil
		}
		// a surrogate pair is two escape sequences, which the error shows: the input waits for the second one
		// while it may be the escape sequence of a low surrogate, or, at the end of the input, it is cut.
		// Without strValid, a high surrogate is taken alone, as encoding/json/jsontext takes it.
		if len() < 12 && isPrefixOfLowSurrogate([6:]) {
			if &strValid != 0 {
				return 0, 0, io.ErrUnexpectedEOF
			}
			if  < 0xdc00 && &strMore != 0 {
				return 6, highCut, nil
			}
		}
		if  < 0xdc00 && len() >= 12 && [6] == '\\' && [7] == 'u' {
			if ,  := scanHex4([6:]);  == nil {
				if  := utf16.DecodeRune(, );  != utf8.RuneError {
					return 12, , nil
				}
			}
		}
		if &strValid != 0 {
			return 0, 0, invalidEscape([:min(len(), 12)], "surrogate pair")
		}
		return 6, -1, nil
	}
	return 0, 0, invalidEscape([:2], "escape sequence")
}

// isPrefixOfLowSurrogate reports whether b may be the start of the escape sequence of a low surrogate, from
// \udc00 to \udfff.
func isPrefixOfLowSurrogate( []byte) bool {
	for ,  := range  {
		switch {
		case  == 0 &&  != '\\',  == 1 &&  != 'u',  == 2 && |0x20 != 'd':
			return false
		case  == 3 && (hexValue() < 0xc),  > 3 && hexValue() < 0:
			return false
		}
	}
	return true
}

// hex4 is the value of the 4 hexadecimal digits at the start of b, or -1 if one is not a digit: the digits are
// taken at once, as a byte which is not a digit is negative in the table, and so is their OR.
func hex4( []byte) rune {
	, , ,  := hexTable[[0]], hexTable[[1]], hexTable[[2]], hexTable[[3]]
	if ||| < 0 {
		return -1
	}
	return rune()<<12 | rune()<<8 | rune()<<4 | rune()
}

// scanHex4 is the value of the escape sequence \uXXXX at the start of b.
func scanHex4( []byte) (rune, error) {
	if len() >= 6 {
		if  := hex4([2:]);  >= 0 {
			return , nil
		}
	}
	var  rune
	for  := 2;  < 6; ++ {
		if  == len() {
			return 0, io.ErrUnexpectedEOF
		}
		 := hexValue([])
		if  < 0 {
			return 0, invalidEscape([:min(len(), 6)], "escape sequence")
		}
		 = <<4 | rune()
	}
	return , nil
}

func hexValue( byte) int {
	return int(hexTable[])
}

// hexTable is the value of each byte as a hexadecimal digit, or -1.
var hexTable = func() [256]int8 {
	var  [256]int8
	for  := range  {
		switch {
		case '0' <=  &&  <= '9':
			[] = int8( - '0')
		case 'a' <=  &&  <= 'f':
			[] = int8( - 'a' + 10)
		case 'A' <=  &&  <= 'F':
			[] = int8( - 'A' + 10)
		default:
			[] = -1
		}
	}
	return 
}()

// appendUnquoted appends the value of the JSON string s, which scanString took with the flags f without an
// error: an escaped surrogate which is not in a pair and invalid UTF-8 are appended as U+FFFD. dst doesn't
// overlap s.
func appendUnquoted(,  []byte,  strFlags) []byte {
	 := [1 : len()-1]
	 := len()
	if &strEscaped != 0 {
		 = jsonstring.AppendUnescaped(, )
	} else {
		 = append(, ...)
	}
	if &strInvalidUTF8 != 0 {
		// the value of an escape sequence is valid UTF-8, which the bytes before or after it don't make invalid
		 = jsonstring.ReplaceInvalidUTF8(, )
	}
	return 
}

// escapeFlags are the characters which a quoted string escapes besides the ones which JSON requires.
type escapeFlags uint8

const (
	escapeHTML escapeFlags = 1 << iota // '<', '>' and '&'
	escapeJS                           // U+2028 and U+2029
)

func escapesOf( *config) escapeFlags {
	var  escapeFlags
	if .Has(escapeForHTML) {
		 |= escapeHTML
	}
	if .Has(escapeForJS) {
		 |= escapeJS
	}
	return 
}

// appendQuoted appends s as a JSON string of the canonical form of RFC 8785, section 3.2.2.2, with the
// escapes of esc. Invalid UTF-8 is written as U+FFFD, and reported by false.
func appendQuoted( []byte,  string,  escapeFlags) ([]byte, bool) {
	return jsonstring.AppendQuoted(jsonstring.TextEscaper(&escapeHTML != 0, &escapeJS != 0), , )
}

// overlaps reports whether the bytes of a and the array of b, to its capacity, share memory.
func overlaps(,  []byte) bool {
	if len() == 0 || cap() == 0 {
		return false
	}
	,  := uintptr(unsafe.Pointer(unsafe.SliceData())), uintptr(unsafe.Pointer(unsafe.SliceData()))
	return  < +uintptr(cap()) &&  < +uintptr(len())
}

// readOnlyBytes is the bytes of s, a string or a []byte, without a copy: they must not be written to. A string
// and a slice both start with the pointer to their bytes, which has the length after it.
func readOnlyBytes[ ~[]byte | ~string]( ) []byte {
	return unsafe.Slice(*(**byte)(unsafe.Pointer(&)), len())
}

// rawStringKept reports whether appendRawString appends the string s as it is.
func rawStringKept( []byte,  strFlags,  escapeFlags,  bool) bool {
	return ( || &strNonCanonical == 0) && ( == 0 || !needsExtraEscape(, ))
}

// appendRawString appends the JSON string s, which scanString took with the flags f, as the options want it:
// requoted unless it is canonical, or as it is with PreserveRawStrings, whose escapes are kept and whose invalid
// UTF-8 is kept as it is; the characters of esc are escaped in any case.
func appendRawString(,  []byte,  strFlags,  escapeFlags,  bool) []byte {
	if rawStringKept(, , , ) {
		return append(, ...)
	}
	if ! {
		var  [64]byte
		 := appendUnquoted([:0], , )
		, _ = appendQuoted(, unsafe.String(unsafe.SliceData(), len()), )
		return 
	}
	 := 0
	for  := 0;  < len(); {
		 := []
		switch {
		case  == '\\':
			 += 2 // an escape sequence, whose second character is not one of esc
			continue
		case  == '<' ||  == '>' ||  == '&':
			if &escapeHTML != 0 {
				 = append(, [:]...)
				 = appendEscapedHTML(, )
				++
				 = 
				continue
			}
		case  == 0xe2 && &escapeJS != 0 && +2 < len() && [+1] == 0x80 && ([+2] == 0xa8 || [+2] == 0xa9):
			 = append(, [:]...)
			 = append(, `\u202`...)
			 = append(, hexDigits[[+2]-0xa0])
			 += 3
			 = 
			continue
		}
		++
	}
	return append(, [:]...)
}

func appendEscapedHTML( []byte,  byte) []byte {
	return append(, '\\', 'u', '0', '0', hexDigits[>>4], hexDigits[&0xf])
}

// needsExtraEscape reports whether the string s has a character of esc which is not escaped.
func needsExtraEscape( []byte,  escapeFlags) bool {
	for  := 0;  < len(); ++ {
		switch  := []; {
		case  == '\\':
			++
		case  == '<' ||  == '>' ||  == '&':
			if &escapeHTML != 0 {
				return true
			}
		case  == 0xe2:
			if &escapeJS != 0 && +2 < len() && [+1] == 0x80 && ([+2] == 0xa8 || [+2] == 0xa9) {
				return true
			}
		}
	}
	return false
}

// appendFloatText appends f as a JSON number of the given precision, as ECMA-262 formats numbers, except that
// -0 is -0: NaN and the infinities are appended as "NaN", "Infinity" and "-Infinity", without quotes.
func appendFloatText( []byte,  float64,  int) []byte {
	switch {
	case math.IsNaN():
		return append(, "NaN"...)
	case math.IsInf(, +1):
		return append(, "Infinity"...)
	case math.IsInf(, -1):
		return append(, "-Infinity"...)
	}
	return floatfmt.AppendFloat(, , )
}

// appendCanonicalNumber appends the JSON number b in the canonical form of RFC 8785: as a float64, saturated at
// the largest finite values, with -0 as 0.
func appendCanonicalNumber(,  []byte) []byte {
	 := parseFloat64()
	if math.IsInf(, 0) {
		 = math.Copysign(math.MaxFloat64, )
	}
	if  == 0 {
		 = 0
	}
	return floatfmt.AppendFloat(, , 64)
}