package jsonstring

import (
	

	
)

// The scan of a string for a byte to escape by AVX2, 32 bytes at a time.

//go:noescape
func scanStringAVX2( unsafe.Pointer,  int,  *nibbleTables) int

//go:noescape
func escapeStringAVX2(,  unsafe.Pointer,  int,  *nibbleTables,  *[256]uint64) (,  int)

//go:noescape
func escapeUTF8AVX2(,  unsafe.Pointer,  int,  *nibbleTables,  *[256]uint64,  *utf8Tables) (,  int)

// hasEscapeLoop is whether appendEscapedSIMD escapes: whether the CPU has AVX2.
var hasEscapeLoop = runtime.HasAVX2

// escapeSegmentLength is the number of the bytes of a string which appendEscapedSIMD escapes by one call of the
// loop, which has room for 6 bytes of every byte: it bounds the growth of the buffer for a long string.
const escapeSegmentLength = 1024

// appendEscapedSIMD appends the string escaped, 32 bytes at a time, as the appendString functions do by the
// tables of their options, and returns the number of the bytes of the string it appended. It stops at a byte
// which the caller escapes or when fewer than 32 bytes remain. If UTF-8 is normalized, tables are the ones of
// the bytes of ASCII to escape, and the bytes which are not ASCII are validated: it stops at the start of a
// character in a block of 32 bytes with invalid UTF-8, U+2028 or U+2029. The CPU has AVX2.
func appendEscapedSIMD( []byte,  string,  *nibbleTables,  bool) ([]byte, int) {
	 := 0
	for len()- >= 32 {
		 := min(len()-, escapeSegmentLength)
		if  := 6* + 32; cap()-len() <  {
			 = growForString(, )
		}
		 := unsafe.Add(unsafe.Pointer(unsafe.SliceData()), len())
		 := unsafe.Add(unsafe.Pointer(unsafe.StringData()), )
		var ,  int
		if  {
			,  = escapeUTF8AVX2(, , , , &escapeSequences, &utf8ValidationTables)
		} else {
			,  = escapeStringAVX2(, , , , &escapeSequences)
		}
		 = [:len()+]
		 += 
		if +32 <=  {
			// stopped at a byte which the caller escapes
			break
		}
	}
	return , 
}

// minSIMDScanLength is the length from which a string is scanned by SIMD: the setup of the registers costs
// about as much as a few words of the scalar scan.
const minSIMDScanLength = 32

// maxOnePassLength is the length of the longest string which AppendString looks at and copies in one pass:
// a longer one is looked at by SIMD, which then costs less, and copied after.
const maxOnePassLength = minSIMDScanLength - 1

// scanBytesSIMD is whether a byte of the n bytes at src is in the tables, by SIMD. The second result is false
// if the CPU doesn't support it or n is small, and the bytes are not looked at. It is inlined, so that
// AppendString calls the scan itself.
func scanBytesSIMD( unsafe.Pointer,  int,  *nibbleTables) (bool, bool) {
	if !runtime.HasAVX2 ||  < minSIMDScanLength {
		return false, false
	}
	return scanStringAVX2(, , ) != 0, true
}