package encoder

import (
	
	
	
	

	
)

// The output of a marshaler is compacted and validated, as encoding/json does. Most of the outputs are compact
// already, so they are copied as they are after being checked: a scan by SIMD finds the bytes which would have
// to be rewritten or looked at, and a walk of the structure without a write validates the rest, the escapes of
// the strings included. The characters which compact escapes for HTML are escaped as the output is copied.
// Anything else is left to compact, which rewrites and reports the errors.

// controlChars are the control characters, which compact removes as white space or reports as errors: an output
// with one is left to compact. lookedAtByCompact are those and the bytes which the check must look at: an
// escape, whose sequence is validated, and, if HTML is escaped, the characters which compact escapes then:
// '<', '>', '&' and the first byte of U+2028 and U+2029, which starts other characters as well. Most of the
// outputs have none of them: their strings are walked to the next quote at once and they are copied as they are.
var (
	controlChars      = jsonstring.NewByteClass()
	lookedAtByCompact = [2]*jsonstring.ByteClass{
		jsonstring.NewByteClass('\\'),
		jsonstring.NewByteClass('\\', '<', '>', '&', 0xe2),
	}
)

// The walks of the strings of an output, as the type argument of isCompactJSON: each walk is compiled into a
// function of its own, so that the walk of the plain strings, which most of the outputs have, has neither a
// branch nor a call for the escapes in its loop. The types differ by their sizes, which the compiler knows for
// each of them: the branch on the size is resolved when the function of a walk is compiled.
type (
	// plainStrings have no escape: a string ends at the next quote.
	plainStrings struct{}
	// escapedStrings may have escapes, which are validated.
	escapedStrings struct{ _ byte }
)

// maxDepthOfCompactScan is the nesting up to which isCompactJSON scans the output: a deeper one is compacted.
const maxDepthOfCompactScan = 64

// appendCompactOutput appends src, the output of a marshaler, to dst as compact appends it, if src is compact
// and valid JSON, and returns false without appending if it may not be: then src is to be compacted. The output
// of a trusted marshaler, valid and compact, is appended as it is if compact leaves it so.
func appendCompactOutput(,  []byte, ,  bool) ([]byte, bool) {
	if len() == 0 {
		return , false
	}
	 := 0
	if  {
		 = 1
	}
	if !lookedAtByCompact[].Has() {
		if ! && !isCompactJSON[plainStrings]() {
			return , false
		}
		return append(, ...), true
	}
	if controlChars.Has() || !isCompactJSON[escapedStrings]() {
		return , false
	}
	if  {
		return jsonstring.AppendHTMLEscaped(, ), true
	}
	return append(, ...), true
}

// isCompactJSON is whether src, which has no control character, is valid JSON without a byte to remove, whose
// strings are walked as S tells.
func isCompactJSON[ plainStrings | escapedStrings]( []byte) bool {
	var  
	 := unsafe.Sizeof() == unsafe.Sizeof(plainStrings{})
	var  [maxDepthOfCompactScan]byte // the closing brackets of the values being read
	 := 0
	 := len()
	 := 0
	for {
		// a value.
		if  >=  {
			return false
		}
		switch  := []; {
		case  == '"':
			if  {
				 = quoteEnd(, +1)
			} else {
				 = escapedQuoteEnd(, +1)
			}
			if  < 0 {
				return false
			}
		case  == '{':
			if  == maxDepthOfCompactScan {
				return false
			}
			[] = '}'
			++
			++
			if  <  && [] == '}' {
				++
				--
				break
			}
			// a key.
			if  >=  || [] != '"' {
				return false
			}
			if  {
				 = quoteEnd(, +1)
			} else {
				 = escapedQuoteEnd(, +1)
			}
			if  < 0 {
				return false
			}
			if  >=  || [] != ':' {
				return false
			}
			++
			continue
		case  == '[':
			if  == maxDepthOfCompactScan {
				return false
			}
			[] = ']'
			++
			++
			if  <  && [] == ']' {
				++
				--
				break
			}
			continue
		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'):
			 := numberEnd(, )
			if  < 0 {
				return false
			}
			 = 
		default:
			return false
		}
		// after a value.
		for {
			if  == 0 {
				return  == 
			}
			if  >=  {
				return false
			}
			switch [] {
			case ',':
				++
				if [-1] == '}' {
					// a key.
					if  >=  || [] != '"' {
						return false
					}
					if  {
						 = quoteEnd(, +1)
					} else {
						 = escapedQuoteEnd(, +1)
					}
					if  < 0 {
						return false
					}
					if  >=  || [] != ':' {
						return false
					}
					++
				}
			case [-1]:
				--
				++
				continue
			default:
				return false
			}
			break
		}
	}
}

// quoteEnd returns the index after the quote which ends the string whose content starts at i, or -1.
// The string has no escape, so the quote is the next one. Most of the strings are short, so the quote is
// looked for by words here, not by a call. The words are read as little-endian ones, so that the lowest byte
// found by bits.TrailingZeros64 is the first one in memory on a big-endian machine too; on a little-endian one
// the read is a load as it is.
func quoteEnd( []byte,  int) int {
	 := len()
	 := unsafe.Pointer(unsafe.SliceData())
	for ; +8 <= ;  += 8 {
		 := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(, ))[:]) ^ (lsb * '"')
		if  := ( - lsb) &^  & msb;  != 0 {
			return  + bits.TrailingZeros64()/8 + 1
		}
	}
	for ;  < ; ++ {
		if [] == '"' {
			return  + 1
		}
	}
	return -1
}

// escapedQuoteEnd is quoteEnd for a string which may have escapes, which are validated.
func escapedQuoteEnd( []byte,  int) int {
	 := len()
	 := unsafe.Pointer(unsafe.SliceData())
	for {
		for ; +8 <= ;  += 8 {
			 := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(, ))[:])
			 :=  ^ (lsb * '"')
			 :=  ^ (lsb * '\\')
			// the lowest bit of the mask of each byte is exact, so the lowest one of both is.
			if  := ((-lsb)&^ | (-lsb)&^) & msb;  != 0 {
				 += bits.TrailingZeros64() / 8
				break
			}
		}
		for ;  <  && [] != '"' && [] != '\\'; ++ {
		}
		if  >=  {
			return -1
		}
		if [] == '"' {
			return  + 1
		}
		 = escapeEnd(, +1)
		if  < 0 {
			return -1
		}
	}
}

// escapeEnd returns the index after the escape of a string whose backslash is before i, or -1 if it is not an
// escape of JSON.
func escapeEnd( []byte,  int) int {
	if  >= len() {
		return -1
	}
	switch [] {
	case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
		return  + 1
	case 'u':
		if +5 > len() {
			return -1
		}
		for ,  := range [+1 : +5] {
			if !('0' <=  &&  <= '9' || 'a' <=  &&  <= 'f' || 'A' <=  &&  <= 'F') {
				return -1
			}
		}
		return  + 5
	}
	return -1
}

// numberEnd returns the index after the number which starts at i, or -1 if it is not a number of JSON.
func numberEnd( []byte,  int) int {
	 := len()
	if [] == '-' {
		++
		if  >=  {
			return -1
		}
	}
	switch {
	case [] == '0':
		++
	case '1' <= [] && [] <= '9':
		++
		for  <  && '0' <= [] && [] <= '9' {
			++
		}
	default:
		return -1
	}
	if  <  && [] == '.' {
		++
		if  >=  || [] < '0' || [] > '9' {
			return -1
		}
		for  <  && '0' <= [] && [] <= '9' {
			++
		}
	}
	if  <  && ([] == 'e' || [] == 'E') {
		++
		if  <  && ([] == '+' || [] == '-') {
			++
		}
		if  >=  || [] < '0' || [] > '9' {
			return -1
		}
		for  <  && '0' <= [] && [] <= '9' {
			++
		}
	}
	return 
}