package encoder

import (
	
	
	
	
	

	
)

// The raw value which a method or a function of the v2 semantics returns is formatted as the options want it,
// which checks it as well: valid JSON, valid UTF-8 and no duplicate names. Most of the values are compact
// already, which are checked here by a walk, as the outputs of the marshalers of v1 are ( see
// appendCompactOutput ), and appended as they are, but for the strings with escapes, which are written again in
// the form of the formatting: the escapes which it doesn't write are written as the characters they are.

// escapedInRaw are the characters which the escaping of the options escapes, in a raw value which is appended
// by the formatting otherwise ( see AppendFormattedRaw ): U+2028 and U+2029 ( EscapeForJS ), whose first byte is
// 0xe2, and '<', '>' and '&' ( EscapeForHTML ). The control characters, which are in each class, are not
// appended here anyway.
var escapedInRaw = [4]*jsonstring.ByteClass{
	nil,
	jsonstring.NewByteClass(0xe2),
	jsonstring.NewByteClass('<', '>', '&'),
	jsonstring.NewByteClass('<', '>', '&', 0xe2),
}

// notPlainRaw are the bytes which aren't ASCII and the control characters, which the strings of a raw value are
// scanned for if it has them ( see rawWalk.stringEnd ), and notPureRaw those and the escapes, which they are
// scanned for if it has them: most values have none, and their strings end at the next quote.
var (
	notPlainRaw = jsonstring.NewByteClass(highBytes()...)
	notPureRaw  = jsonstring.NewByteClass(append(highBytes(), '\\')...)
)

func highBytes() []byte {
	 := make([]byte, 0, 129)
	for  := 0x80;  <= 0xff; ++ {
		 = append(, byte())
	}
	return 
}

// maxNamesOfRawWalk is the number of the names of the objects being read, and maxDepthOfRawWalk the depth of the
// values, up to which a raw value is appended here: a larger one is formatted.
const (
	maxNamesOfRawWalk = 64
	maxDepthOfRawWalk = 64
)

// rawLevels are the levels of the walk of a raw value ( see rawWalk ), which the runtime context keeps, so that
// they are not cleared for every value: the walk reads only what it wrote. stack are the closing brackets of the
// values being read; names are the offsets of the names of the objects being read, and first the index in names
// of the first name of each level.
type rawLevels struct {
	stack [maxDepthOfRawWalk]byte
	first [maxDepthOfRawWalk]int32
	names [maxNamesOfRawWalk]int32
}

// AppendFormattedRaw appends src, a raw value, to dst as the formatting of the v2 semantics with the escaping of
// ctx appends it, and reports true, if src is compact, valid JSON whose strings are valid UTF-8 without a control
// character or an escape of a surrogate, whose names have no escape, and whose objects have no duplicate names.
// Otherwise it reports false, and src is to be formatted: dst may have been written after its length then.
//
// It reads src once, and once more for the escaping of the options, if any, and for UTF-8, if src has a byte
// which is not ASCII.
func ( *RuntimeContext, ,  []byte) ([]byte, bool) {
	 := .Option.Flag
	 := 0
	if &NormalizeUTF8Option != 0 {
		 |= 1
	}
	if &HTMLEscapeOption != 0 {
		 |= 2
	}
	if len() == 0 || ( != 0 && escapedInRaw[].Has()) {
		return , false
	}
	// a value of ASCII without a control character and an escape, as most are, is found by SIMD: its strings end
	// at the next quote, and it is appended as it is. The strings of the other values of ASCII without a control
	// character are scanned for the quotes and the escapes only.
	if !notPureRaw.Has() {
		if !walkRaw[plainStrings](nil, , .levelsOfRaw()) {
			return , false
		}
		return append(, ...), true
	}
	 := rawWalk{ctx: , src: , dst: , ascii: true, escape: , plain: !notPlainRaw.Has()}
	if !walkRaw[escapedStrings](&, , .levelsOfRaw()) || !(.ascii || utf8.Valid()) {
		return , false
	}
	return append(.dst, [.copied:]...), true
}

// rawWalk is the state of the walk of AppendFormattedRaw over src: dst is the output, which has src up to copied,
// with the strings of escapes before it written again.
type rawWalk struct {
	ctx    *RuntimeContext
	src    []byte
	dst    []byte
	copied int
	// ascii is whether every byte read is ASCII.
	ascii bool
	// escape is the escaping of the options ( see escapedInRaw ), and plain is whether src has only ASCII
	// without a control character.
	escape int
	plain  bool
}

// walkRaw reports whether src is a value which AppendFormattedRaw appends, whose levels are read in lv. The
// strings are walked as S tells: by w, which writes the strings of escapes again, or, for plainStrings, to the
// next quote, without w, which is nil, for src of ASCII without a control character and an escape.
//
// The walk goes from a value to what follows it by the labels: a name of an object is read only where one is next,
// without a branch for it at every value.
func walkRaw[ plainStrings | escapedStrings]( *rawWalk,  []byte,  *rawLevels) bool {
	var  
	 := unsafe.Sizeof() == unsafe.Sizeof(plainStrings{})
	 := len()
	// the state of the levels, in registers: first is the index of the first name of the innermost level, whose
	// value lv.first keeps for the level around it.
	, ,  := 0, int32(0), int32(0)
	 := 0
:
	if  >=  {
		return false
	}
	switch  := []; {
	case  == '"':
		if  {
			if  = quoteEnd(, +1);  < 0 {
				return false
			}
			break
		}
		,  := .stringEnd( + 1)
		if  < 0 {
			return false
		}
		if  != 0 && !.requote(, , ) {
			return false
		}
		 = 
	case  == '{':
		if  == maxDepthOfRawWalk {
			return false
		}
		.stack[] = '}'
		.first[],  = , 
		++
		++
		if  <  && [] == '}' {
			++
			--
			 = .first[]
			break
		}
		goto 
	case  == '[':
		if  == maxDepthOfRawWalk {
			return false
		}
		.stack[] = ']'
		.first[],  = , 
		++
		++
		if  <  && [] == ']' {
			++
			--
			 = .first[]
			break
		}
		goto 
	case  == 't':
		if !bytes.HasPrefix([:], []byte("true")) {
			return false
		}
		 += 4
	case  == 'f':
		if !bytes.HasPrefix([:], []byte("false")) {
			return false
		}
		 += 5
	case  == 'n':
		if !bytes.HasPrefix([:], []byte("null")) {
			return false
		}
		 += 4
	case  == '-' || ('0' <=  &&  <= '9'):
		if  = numberEnd(, );  < 0 {
			return false
		}
	default:
		return false
	}
	// after a value.
	for {
		if  == 0 {
			return  == 
		}
		if  >=  {
			return false
		}
		switch [] {
		case ',':
			++
			if .stack[-1] == '}' {
				goto 
			}
			goto 
		case .stack[-1]:
			--
			,  = , .first[]
			++
		default:
			return false
		}
	}
:
	// a name, which must be new in the object, before its value.
	if  >=  || [] != '"' ||  == maxNamesOfRawWalk {
		return false
	}
	{
		var ,  int
		if  {
			 = quoteEnd(, +1)
		} else {
			,  = .stringEnd( + 1)
		}
		if  < 0 ||  != 0 {
			return false
		}
		 :=  - 
		for ,  := range .names[:] {
			// the name with its quotes, which has no escape: the quote ends the one before as well. The first
			// characters, which differ for most names, are compared without a call.
			if  := int(); + <  && [+1] == [+1] && [+-1] == '"' && bytes.Equal([:+], [:]) {
				return false
			}
		}
		.names[] = int32()
		++
		if  >=  || [] != ':' {
			return false
		}
		 =  + 1
	}
	goto 
}

// stringEnd returns the index after the quote which ends the string whose content starts at i, and whether the
// string has an escape; or -1 if the string has a control character or an invalid escape, or an escape of a
// surrogate, which the formatting reports or writes as it is, or doesn't end. It clears ascii if the string has a
// byte which is not ASCII. The bytes are looked at by words: the lowest byte of the mask of each kind is exact.
func ( *rawWalk) ( int) (int, int) {
	if .plain {
		return .plainStringEnd()
	}
	 := .src
	 := len()
	 := unsafe.Pointer(unsafe.SliceData())
	 := 0 // the index of the first escape
	for {
		for ; +8 <= ;  += 8 {
			 := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(, ))[:])
			 :=  ^ (lsb * '"')
			 :=  ^ (lsb * '\\')
			 := ((-lsb)&^ | (-lsb)&^ | (-lsb*0x20)&^) & msb
			if .ascii {
				 |=  & msb
			}
			if  != 0 {
				 += bits.TrailingZeros64() / 8
				break
			}
		}
		for ;  < ; ++ {
			if  := [];  == '"' ||  == '\\' ||  < 0x20 || ( >= 0x80 && .ascii) {
				break
			}
		}
		if  >=  {
			return -1, 0
		}
		switch  := []; {
		case  == '"':
			return  + 1, 
		case  == '\\':
			if +1 <  && [+1] == 'u' && +3 <  && ([+2]|0x20) == 'd' && [+3] >= '8' {
				// \uD800 to \uDFFF: a surrogate, which the formatting checks with the one after it.
				return -1, 0
			}
			if  == 0 {
				 = 
			}
			if  = escapeEnd(, +1);  < 0 {
				return -1, 0
			}
		case  >= 0x80:
			.ascii = false
			++
		default:
			return -1, 0
		}
	}
}

// plainStringEnd is stringEnd for src of ASCII without a control character: the words are looked at for the quote
// and the escape only.
func ( *rawWalk) ( int) (int, int) {
	 := .src
	 := len()
	 := unsafe.Pointer(unsafe.SliceData())
	 := 0 // the index of the first escape
	for {
		for ; +8 <= ;  += 8 {
			 := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(, ))[:])
			 :=  ^ (lsb * '"')
			 :=  ^ (lsb * '\\')
			if  := ((-lsb)&^ | (-lsb)&^) & msb;  != 0 {
				 += bits.TrailingZeros64() / 8
				break
			}
		}
		for ;  <  && [] != '"' && [] != '\\'; ++ {
		}
		if  >=  {
			return -1, 0
		}
		if [] == '"' {
			return  + 1, 
		}
		if +1 <  && [+1] == 'u' && +3 <  && ([+2]|0x20) == 'd' && [+3] >= '8' {
			// \uD800 to \uDFFF: a surrogate, which the formatting checks with the one after it.
			return -1, 0
		}
		if  == 0 {
			 = 
		}
		if  = escapeEnd(, +1);  < 0 {
			return -1, 0
		}
	}
}

// requote writes the string src[start:end], which has escapes, as the formatting writes it: an escaped character
// which needs no escape as it is, and the others by the escapes of the escapers of the strings, in one pass. With
// the escaping of the options, the string is written by the escaper of the options.
//
// first is the index of the first escape of the string, before which it is copied as it is.
func ( *rawWalk) (, ,  int) bool {
	if .escape != 0 {
		.dst = append(.dst, .src[.copied:]...)
		.copied = 
		 := .ctx
		.MarshalBuf = jsonstring.AppendUnescaped(.MarshalBuf[:0], .src[+1:-1])
		var  bool
		.dst,  = jsonstring.AppendQuoted(textEscaper(), .dst, unsafe.String(unsafe.SliceData(.MarshalBuf), len(.MarshalBuf)))
		return 
	}
	// the output before the string, the quote and the characters before the first escape.
	 := append(.dst, .src[.copied:]...)
	.copied = 
	// the escapes are valid, of no surrogate ( see stringEnd ), and the rest is checked for UTF-8 with the value.
	 := .src[ : -1]
	for {
		 := bytes.IndexByte(, '\\')
		if  < 0 {
			 = append(, ...)
			break
		}
		 = append(, [:]...)
		,  := rune([+1]), 2
		switch  {
		case 'b':
			 = '\b'
		case 'f':
			 = '\f'
		case 'n':
			 = '\n'
		case 'r':
			 = '\r'
		case 't':
			 = '\t'
		case 'u':
			,  = hexRune([+2:+6]), 6
		}
		switch {
		case  == '"' ||  == '\\' ||  < 0x20:
			 = jsonstring.AppendASCIIEscape(, byte())
		case  < utf8.RuneSelf:
			 = append(, byte())
		default:
			 = utf8.AppendRune(, )
		}
		 = [+:]
	}
	.dst = append(, '"')
	return true
}

// hexRune returns the character of the four hexadecimal digits of an escape, which are valid.
func hexRune( []byte) rune {
	var  rune
	for ,  := range [:4] {
		switch {
		case  <= '9':
			 -= '0'
		case  <= 'F':
			 -= 'A' - 10
		default:
			 -= 'a' - 10
		}
		 = <<4 | rune()
	}
	return 
}