package decoder

import (
	
	
	
	
	
	

	
	
)

type stringDecoder struct {
	structName string
	fieldName  string
	// typ is the type of the string, which the type errors report.
	typ reflect.Type
}

func newStringDecoder(,  string) *stringDecoder {
	return &stringDecoder{
		structName: ,
		fieldName:  ,
		typ:        reflect.TypeOf(""),
	}
}

func ( *stringDecoder) ( string,  int64) *errors.UnmarshalTypeError {
	return &errors.UnmarshalTypeError{
		Value:  ,
		Type:   reflect.TypeOf(""),
		Offset: ,
		Struct: .structName,
		Field:  .fieldName,
	}
}

func ( *stringDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	var (
		   string
		   int64
		  bool
		 error
	)
	 := .Buf
	if  := skipWhiteSpace(, ); [] == '"' {
		, , ,  = .decodeStringField(, +1)
	} else {
		, , ,  = .decodeStringValue(, )
	}
	if  != nil {
		return 0, 
	}
	if  {
		**(**string)(unsafe.Pointer(&)) = 
	}
	return , nil
}

func ( *stringDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	, ,  := .decodeByte(.Buf, )
	if  != nil {
		return nil, 0, 
	}
	if  == nil {
		return [][]byte{nullbytes}, , nil
	}
	return [][]byte{}, , nil
}

// stringInfo is what scanString found in a string.
type stringInfo struct {
	// firstEscape is the offset of the first backslash in the bytes of the string, or -1 if it has no escape:
	// its bytes are the ones of the value then.
	firstEscape int
	// nonASCII is whether a byte of the string is not ASCII: the string may be invalid UTF-8.
	nonASCII bool
}

// decodeByte returns the bytes of the string at cursor, or nil for null: a part of buf, or a slice of their own if
// the string has an escape or invalid UTF-8 ( see decodeLiteral ).
func ( *stringDecoder) ( []byte,  int64) ([]byte, int64, error) {
	, , ,  := .scanString(, )
	if  < 0 {
		, , ,  = .scanStringRest(, , --1, )
	}
	if  != nil ||  == nil {
		return , , 
	}
	return decodeLiteral(, ), , nil
}

// unescapeString returns the string of the literal, which has an escape: it is decoded into the scratch bytes of the
// context, and copied, so that the string has the bytes of its length only, which are not zeroed before they are
// written, and the buffer is not written. A literal too long for the scratch bytes is decoded into bytes of its own,
// which the string is.
func ( *RuntimeContext) ( []byte,  stringInfo) string {
	if len() > maxUnescapeScratchSize {
		 := decodeLiteral(, )
		return unsafe.String(unsafe.SliceData(), len())
	}
	if cap(.unescaped) < len() {
		// twice as large as before, so that strings of growing lengths make few of them
		.unescaped = make([]byte, min(max(len(), 2*cap(.unescaped)), maxUnescapeScratchSize))
	}
	 := jsonstring.UnescapeTo(unsafe.Pointer(unsafe.SliceData(.unescaped)), , .firstEscape)
	 := .unescaped[:]
	if .nonASCII && !utf8.Valid() {
		return string(coerceUTF8())
	}
	return string()
}

// decodeLiteral decodes the escapes of the literal and replaces its invalid UTF-8, into a slice of its own if it
// has any: the buffer is never written, so that it keeps the input, which is checked again for a syntax error
// ( see Stream.decodeError ).
func decodeLiteral( []byte,  stringInfo) []byte {
	if .firstEscape >= 0 {
		 := make([]byte, len())
		 = [:jsonstring.UnescapeTo(unsafe.Pointer(unsafe.SliceData()), , .firstEscape)]
	}
	if .nonASCII && !utf8.Valid() {
		 = coerceUTF8()
	}
	return 
}

// validLiteral returns the literal of a string without an escape, whose bytes are not all ASCII, with its invalid
// UTF-8 replaced ( see decodeLiteral ).
func validLiteral( []byte) []byte {
	if !utf8.Valid() {
		return coerceUTF8()
	}
	return 
}

// decodeStringValue is decodeString for the value of a string: a value of another kind is a type error, which is
// recorded, and skipped ( see skipOtherValue ). It is a function of its own, so that the decoding of the other
// strings, as the keys, is the one it was, and that Decode keeps nothing across its call.
func ( *stringDecoder) ( *RuntimeContext,  int64) (string, int64, bool, error) {
	, , ,  := .scanString(.Buf, )
	if  < 0 {
		return .decodeStringRest(, , --1, )
	}
	if  != nil {
		return .skipOtherValue(, )
	}
	if  == nil {
		return "", , false, nil
	}
	if .firstEscape >= 0 {
		return .unescapeString(, ), , true, nil
	}
	if .nonASCII {
		 = validLiteral()
	}
	return .makeString(), , true, nil
}

// decodeStringField is decodeStringValue for the string whose bytes start at start, after its quote, which the decoder
// of a string field decodes. Its words are looked at for their end, an escape and a control byte, and, until the
// first one is met, a byte which is not ASCII: the words of a plain ASCII string are looked at for nothing more, and
// its bytes are the string. An escape is validated where it is met, and a byte which is not ASCII makes the words
// look past such bytes, so that any string is scanned once. The string is then decoded as decodeStringValue decodes
// it: an escaped string through the scratch bytes ( see unescapeString ), a long one from where the words stop ( see
// decodeStringRest ). Where the CPU has a SIMD scan, the words are looked at in the first 64 bytes only, after which
// a long string is scanned by SIMD. An error in the string is a syntax error of the string.
func ( *stringDecoder) ( *RuntimeContext,  int64) (string, int64, bool, error) {
	 := .Buf
	 := (*sliceHeader)(unsafe.Pointer(&)).data
	 := int64(len())
	 := 
	 := 
	if hasStringSIMD {
		 = min(, +64)
	}
	// The words of a plain ASCII string, which most are, are looked at by this loop, which keeps nothing else: the
	// loop below goes on from the byte it stops at, which is not read again.
	for +8 <=  {
		 := load64(, )
		if  := keyEndBytes() | &msb;  != 0 {
			 += int64(bits.TrailingZeros64() / 8)
			if char(, ) == '"' {
				return .makeString([:]),  + 1, true, nil
			}
			break
		}
		 += 8
	}
	 := int64(-1)
	 := false
	// ascii are the top bits which stop the words at a byte which is not ASCII, until the first one is met.
	 := uint64(msb)
	for {
		 := char(, )
		switch {
		case  == '"':
			,  := [:], +1
			if  < 0 {
				if  {
					 = validLiteral()
				}
				return .makeString(), , true, nil
			}
			return .unescapeString(, stringInfo{firstEscape: int(), nonASCII: }), , true, nil
		case  == '\\':
			if  < 0 {
				 =  - 
			}
			++
			switch char(, ) {
			case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
				++
			case 'u':
				if +5 >=  {
					return "", 0, false, errors.ErrUnexpectedEndOfJSON("escaped string", )
				}
				for  := int64(1);  <= 4; ++ {
					 := char(, +)
					if !(('0' <=  &&  <= '9') || ('a' <=  &&  <= 'f') || ('A' <=  &&  <= 'F')) {
						return "", 0, false, errors.ErrSyntax(fmt.Sprintf("json: invalid character %c in \\u hexadecimal character escape", ), +)
					}
				}
				 += 5
			default:
				return "", 0, false, errors.ErrUnexpectedEndOfJSON("escaped string", )
			}
		case  >= 0x80:
			,  = true, 0
			++
		case  == nul:
			return "", 0, false, errors.ErrUnexpectedEndOfJSON("string", )
		case  < 0x20:
			return "", 0, false, errors.ErrSyntax(fmt.Sprintf("invalid character %s in string literal", quoteChar()), +1)
		default:
			// the words stopped where they may not be read, not at a byte to look at
			if  !=  {
				// the words stopped at wordsEnd, not at a byte to look at: the rest is scanned by SIMD
				return .decodeStringRest(, [:], , stringInfo{firstEscape: int(), nonASCII: })
			}
			++
		}
		for +8 <=  {
			 := load64(, )
			if  := keyEndBytes() | &;  != 0 {
				 += int64(bits.TrailingZeros64() / 8)
				break
			}
			 += 8
		}
	}
}

// skipOtherValue returns the error of scanString for a value which is not a string, or, for a value of another
// kind, which scanString reports by an error at its position, records its type error and skips it. The skipped
// value is not nested in the ones before it: its depth is counted from 0.
//
//go:noinline
func ( *stringDecoder) ( *RuntimeContext,  error) (string, int64, bool, error) {
	var  int64
	switch e := .(type) {
	case *errors.UnmarshalTypeError:
		// a number, an array or an object
		 = .Offset
	case *errors.SyntaxError:
		// true and false start no string
		if  := .Buf[.Offset];  != 't' &&  != 'f' {
			return "", 0, false, 
		}
		 = .Offset
	default:
		return "", 0, false, 
	}
	,  := .skipTypeError(, 0, .typ)
	return "", , false, 
}

// decodeString returns the string at cursor as a value to store, and false for null.
// An escaped string is decoded out of the buffer directly.
func ( *stringDecoder) ( *RuntimeContext,  int64) (string, int64, bool, error) {
	, , ,  := .scanString(.Buf, )
	if  < 0 {
		, , ,  = .scanStringRest(.Buf, , --1, )
	}
	if  != nil ||  == nil {
		return "", , false, 
	}
	if .firstEscape >= 0 {
		return .unescapeString(, ), , true, nil
	}
	if .nonASCII {
		 = validLiteral()
	}
	return .makeString(), , true, nil
}

// plainStringEnd returns the position of the quote which ends the string whose bytes start at start, if its bytes
// are all ASCII and none of them is escaped, and -1 for any other string, which the caller decodes by decodeString.
// Most of the keys and many of the values are such strings: this is their scan alone, eight bytes at a time, with
// nothing to keep about the bytes it passes. A word is read only where the buffer has room for it, so that a string
// at the end of the buffer is left to decodeString too.
func plainStringEnd( []byte,  int64) int64 {
	 := 
	 := int64(len())
	for +8 <=  {
		 := load64(, )
		// keyEndBytes has no false bit before its first true one, and none at a byte which is not ASCII, which the top
		// bits add: the first bit is the first byte which ends the plain bytes.
		if  := keyEndBytes() | &msb;  != 0 {
			 += int64(bits.TrailingZeros64() / 8)
			if [] == '"' {
				return 
			}
			return -1
		}
		 += 8
	}
	return -1
}

// scanString finds the string at cursor, and returns its bytes as they are in buf, the position after it and
// what it found in it, or nil for null.
//
// Most strings are short, and scanned by its loop, which calls nothing so that it keeps its values in the
// registers. After 64 bytes of plain bytes, it stops and returns the bytes of the string so far, -1 minus the
// position it stopped at, and what it found so far: the caller continues the scan by scanStringRest, which scans
// the runs of plain bytes of a long string by SIMD where the CPU has it. The position is negative so that the
// result has no field more, whose return every string would pay for.
func ( *stringDecoder) ( []byte,  int64) ([]byte, int64, stringInfo, error) {
	for {
		switch [] {
		case ' ', '\n', '\t', '\r':
			++
		case '[':
			return nil, 0, stringInfo{}, .errUnmarshalType("array", )
		case '{':
			return nil, 0, stringInfo{}, .errUnmarshalType("object", )
		case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			return nil, 0, stringInfo{}, .errUnmarshalType("number", )
		case '"':
			++
			 := 
			 := (*sliceHeader)(unsafe.Pointer(&)).data
			 := int64(len())
			 := int64(-1)
			// high accumulates the bytes of the string: it is not zero if one of them is not ASCII.
			var  uint64
			// The words are read up to wordsEnd: the end of the buffer, or, where the CPU has a SIMD scan, 64
			// bytes after the start, after which the rest of a long string is left to scanStringRest ( see
			// scanString ). It is looked at once for a string, not for every word.
			 := 
			if hasStringSIMD {
				 = min(, +64)
			}
			for {
				// The words with nothing to look at are skipped eight bytes at a time: a word is read only where
				// the buffer has room for it, so that its end is scanned byte by byte.
				for +8 <=  {
					 := load64(, )
					if  := keyEndBytes();  != 0 {
						 := int64(bits.TrailingZeros64() / 8)
						 |=  & msb & (1<<(uint()*8&63) - 1)
						 += 
						break
					}
					 |=  & msb
					 += 8
				}
				 := char(, )
				switch  {
				case '\\':
					if  < 0 {
						 =  - 
					}
					++
					switch char(, ) {
					case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
						++
					case 'u':
						if +5 >=  {
							return nil, 0, stringInfo{}, errors.ErrUnexpectedEndOfJSON("escaped string", )
						}
						for  := int64(1);  <= 4; ++ {
							 := char(, +)
							if !(('0' <=  &&  <= '9') || ('a' <=  &&  <= 'f') || ('A' <=  &&  <= 'F')) {
								return nil, 0, stringInfo{}, errors.ErrSyntax(fmt.Sprintf("json: invalid character %c in \\u hexadecimal character escape", ), +)
							}
						}
						 += 5
					default:
						return nil, 0, stringInfo{}, errors.ErrUnexpectedEndOfJSON("escaped string", )
					}
				case '"':
					return [:],  + 1, stringInfo{firstEscape: int(), nonASCII: &msb != 0}, nil
				case nul:
					return nil, 0, stringInfo{}, errors.ErrUnexpectedEndOfJSON("string", )
				default:
					if  < 0x20 {
						return nil, 0, stringInfo{}, errors.ErrSyntax(fmt.Sprintf("invalid character %s in string literal", quoteChar()), +1)
					}
					if  !=  {
						// the words stopped at wordsEnd, not at a byte to look at
						return [:], - - 1, stringInfo{firstEscape: int(), nonASCII: &msb != 0}, nil
					}
					 |= uint64()
					++
				}
			}
		case 'n':
			if  := validateNull(, );  != nil {
				return nil, 0, stringInfo{}, 
			}
			 += 4
			return nil, , stringInfo{}, nil
		default:
			return nil, 0, stringInfo{}, errors.ErrInvalidBeginningOfValue([], )
		}
	}
}

// scanStringRest continues the scan of a long string from where scanString stopped, which returned the bytes
// of the string so far, the position it stopped at and what it found so far: the runs of plain bytes are scanned
// by SIMD ( see indexStringSpecial ), and a run near the end of the buffer by words. The escapes are validated as
// scanString does.
func ( *stringDecoder) (,  []byte,  int64,  stringInfo) ([]byte, int64, stringInfo, error) {
	 :=  - int64(len())
	 := int64(.firstEscape)
	var  uint64
	if .nonASCII {
		 = msb
	}
	 := (*sliceHeader)(unsafe.Pointer(&)).data
	 := int64(len())
	for {
		if , ,  := indexStringSpecial(unsafe.Add(, ), int(-));  {
			 |= 
			 += int64()
		} else {
			for +8 <=  {
				 := load64(, )
				if  := keyEndBytes();  != 0 {
					 := int64(bits.TrailingZeros64() / 8)
					 |=  & msb & (1<<(uint()*8&63) - 1)
					 += 
					break
				}
				 |=  & msb
				 += 8
			}
		}
		 := char(, )
		switch  {
		case '\\':
			if  < 0 {
				 =  - 
			}
			++
			switch char(, ) {
			case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
				++
			case 'u':
				if +5 >=  {
					return nil, 0, stringInfo{}, errors.ErrUnexpectedEndOfJSON("escaped string", )
				}
				for  := int64(1);  <= 4; ++ {
					 := char(, +)
					if !(('0' <=  &&  <= '9') || ('a' <=  &&  <= 'f') || ('A' <=  &&  <= 'F')) {
						return nil, 0, stringInfo{}, errors.ErrSyntax(fmt.Sprintf("json: invalid character %c in \\u hexadecimal character escape", ), +)
					}
				}
				 += 5
			default:
				return nil, 0, stringInfo{}, errors.ErrUnexpectedEndOfJSON("escaped string", )
			}
		case '"':
			return [:],  + 1, stringInfo{firstEscape: int(), nonASCII: &msb != 0}, nil
		case nul:
			return nil, 0, stringInfo{}, errors.ErrUnexpectedEndOfJSON("string", )
		default:
			if  < 0x20 {
				return nil, 0, stringInfo{}, errors.ErrSyntax(fmt.Sprintf("invalid character %s in string literal", quoteChar()), +1)
			}
			 |= uint64()
			++
		}
	}
}

// coerceUTF8 returns a copy of the literal in which every byte of an invalid UTF-8 sequence
// is replaced by utf8.RuneError, as encoding/json does.
func coerceUTF8( []byte) []byte {
	return jsonstring.AppendValidUTF8(make([]byte, 0, len()+2*utf8.UTFMax), )
}

// quoteChar formats c as a quoted character literal, as encoding/json does in its errors.
func quoteChar( byte) string {
	if  == '\'' {
		return `'\''`
	}
	if  == '"' {
		return `'"'`
	}
	 := strconv.Quote(string())
	return "'" + [1:len()-1] + "'"
}