package jsonstring

import (
	
	
	
	
	
)

func char( unsafe.Pointer,  int) byte {
	return *(*byte)(unsafe.Add(, ))
}

// HexToInt is the value of each hexadecimal digit, and 0 for any other byte.
var HexToInt = [256]int{
	'0': 0,
	'1': 1,
	'2': 2,
	'3': 3,
	'4': 4,
	'5': 5,
	'6': 6,
	'7': 7,
	'8': 8,
	'9': 9,
	'A': 10,
	'B': 11,
	'C': 12,
	'D': 13,
	'E': 14,
	'F': 15,
	'a': 10,
	'b': 11,
	'c': 12,
	'd': 13,
	'e': 14,
	'f': 15,
}

// UnescapeMap is the byte of each escape sequence of one character after its backslash.
var UnescapeMap = [256]byte{
	'"':  '"',
	'\\': '\\',
	'/':  '/',
	'\'': '\'', // which Unquote takes, as encoding/json does
	'b':  '\b',
	'f':  '\f',
	'n':  '\n',
	'r':  '\r',
	't':  '\t',
}

func unsafeAdd( unsafe.Pointer,  int) unsafe.Pointer {
	return unsafe.Add(, )
}

// copyToBackslash copies the bytes from src up to the first backslash of the n bytes, or all of them, to dst, and
// returns how many it copied: bytes.IndexByte and copy go by vectors. It is not inlined, so that UnescapeTo keeps
// its registers for the short runs, which most are.
//
//go:noinline
func copyToBackslash(,  unsafe.Pointer,  int) int {
	 := unsafe.Slice((*byte)(), )
	if  := bytes.IndexByte(, '\\');  >= 0 {
		 = 
	}
	copy(unsafe.Slice((*byte)(), ), [:])
	return 
}

// UnescapeTo decodes the escapes of the bytes of an escaped string into out, which has room for as many bytes and
// is not the bytes themselves, and returns the length of the result, which is at most the length of the bytes.
//
// The escapes are valid and complete, as a scan of the string checked them, and the array of buf has a byte
// after them, as the closing quote of the string: a pointer moves up to the end of buf. first is the offset of
// the first backslash.
func ( unsafe.Pointer,  []byte,  int) int {
	 := unsafe.Pointer(unsafe.SliceData())
	 := unsafeAdd(, len())
	// the bytes before the first escape, by words: a short string is not worth a call of memmove.
	 := 0
	for ; +8 <= ;  += 8 {
		*(*uint64)(unsafeAdd(, )) = *(*uint64)(unsafeAdd(, ))
	}
	for ;  < ; ++ {
		*(*byte)(unsafeAdd(, )) = *(*byte)(unsafeAdd(, ))
	}
	 := unsafeAdd(, )
	 := unsafeAdd(, )
	for  !=  {
		// The bytes up to the next backslash are copied eight at a time, from the words which are all in the
		// string. A word is written whole, and the output goes on to its backslash: out has the length of buf, and
		// is never ahead of the bytes read, so that a word written at dst ends before out does. A run longer than
		// two words is looked through by bytes.IndexByte and moved by copy, which go by vectors.
		for  := 0; *(*byte)() != '\\' && uintptr()+8 <= uintptr(); ++ {
			if  == 2 {
				 := copyToBackslash(, , int(uintptr()-uintptr()))
				 = unsafeAdd(, )
				 = unsafeAdd(, )
				break
			}
			 := binary.LittleEndian.Uint64((*[8]byte)()[:])
			binary.LittleEndian.PutUint64((*[8]byte)()[:], )
			if  := firstByteMask(, '\\');  != 0 {
				 := bits.TrailingZeros64() / 8
				 = unsafeAdd(, )
				 = unsafeAdd(, )
				break
			}
			 = unsafeAdd(, 8)
			 = unsafeAdd(, 8)
		}
		if  ==  {
			break
		}
		 := char(, 0)
		if  == '\\' {
			 := char(, 1)
			if  != 'u' {
				*(*byte)() = UnescapeMap[]
				 = unsafeAdd(, 2)
				 = unsafeAdd(, 1)
			} else {
				 := HexToInt[char(, 2)]
				 := HexToInt[char(, 3)]
				 := HexToInt[char(, 4)]
				 := HexToInt[char(, 5)]
				 := rune(( << 12) | ( << 8) | ( << 4) | )
				if  >= 0xd800 &&  < 0xdc00 && uintptr()-uintptr() >= 12 {
					if char(, 6) == '\\' && char(, 7) == 'u' {
						 := HexToInt[char(, 8)]
						 := HexToInt[char(, 9)]
						 := HexToInt[char(, 10)]
						 := HexToInt[char(, 11)]
						 := rune(( << 12) | ( << 8) | ( << 4) | )
						if  >= 0xdc00 &&  < 0xe000 {
							 = (-0xd800)<<10 | ( - 0xdc00) + 0x10000
							 = unsafeAdd(, 6)
						}
					}
				}
				var  [utf8.UTFMax]byte
				 := utf8.EncodeRune([:], )
				switch  {
				case 4:
					*(*byte)(unsafeAdd(, 3)) = [3]
					fallthrough
				case 3:
					*(*byte)(unsafeAdd(, 2)) = [2]
					fallthrough
				case 2:
					*(*byte)(unsafeAdd(, 1)) = [1]
					fallthrough
				case 1:
					*(*byte)(unsafeAdd(, 0)) = [0]
				}
				 = unsafeAdd(, 6)
				 = unsafeAdd(, )
			}
		} else {
			*(*byte)() = 
			 = unsafeAdd(, 1)
			 = unsafeAdd(, 1)
		}
	}
	return int(uintptr() - uintptr())
}

// firstByteMask returns the word which has the top bit of the first byte of w which is c, if it has one, and maybe
// the top bits of bytes after it: a subtraction borrows from the next byte only at a byte which is c.
func firstByteMask(,  uint64) uint64 {
	 :=  ^ ( * lsb)
	return ( - lsb) &^  & msb
}

// AppendUnescaped appends the value of the bytes s of a JSON string, between its quotes, to dst, which doesn't
// overlap s. The escapes are valid and complete, as a scan of the string checked them, and the closing quote
// follows s in its array, as UnescapeTo needs.
func (,  []byte) []byte {
	 := bytes.IndexByte(, '\\')
	if  < 0 {
		return append(, ...)
	}
	if cap()-len() < len() {
		 = append([:cap()], make([]byte, len()-(cap()-len()))...)[:len()]
	}
	 := UnescapeTo(unsafe.Add(unsafe.Pointer(unsafe.SliceData()), len()), , )
	return [:len()+]
}

var runeErrBytes = []byte(string(utf8.RuneError))

// AppendValidUTF8 appends b to dst, with every byte of an invalid UTF-8 sequence replaced by utf8.RuneError, as
// encoding/json does.
func (,  []byte) []byte {
	for  := 0;  < len(); {
		,  := utf8.DecodeRune([:])
		if  == utf8.RuneError &&  == 1 {
			 = append(, runeErrBytes...)
		} else {
			 = append(, [:+]...)
		}
		 += 
	}
	return 
}

// ReplaceInvalidUTF8 replaces every byte of an invalid UTF-8 sequence of b[start:] by utf8.RuneError.
func ( []byte,  int) []byte {
	if utf8.Valid([:]) {
		return 
	}
	return AppendValidUTF8([:], bytes.Clone([:]))
}

// Unquote returns the value of the JSON string lit, with its quotes, and true; or false if lit is not one. It
// takes lit as encoding/json takes the string of a ,string option and of an encoding.TextUnmarshaler, which isn't
// checked before: it takes the escape \' too. The value is lit between its quotes if it needs no change, else
// new bytes, with every byte of invalid UTF-8 replaced by utf8.RuneError.
func ( []byte) ([]byte, bool) {
	if len() < 2 || [0] != '"' || [len()-1] != '"' {
		return nil, false
	}
	 := [1 : len()-1]
	for  := 0;  < len(); ++ {
		switch  := []; {
		case  == '"' ||  < ' ':
			return nil, false
		case  == '\\':
			if +1 == len() {
				return nil, false
			}
			switch [+1] {
			case '"', '\\', '/', '\'', 'b', 'f', 'n', 'r', 't':
				++
			case 'u':
				if +6 > len() || !isHex([+2]) || !isHex([+3]) || !isHex([+4]) || !isHex([+5]) {
					return nil, false
				}
				 += 5
			default:
				return nil, false
			}
		}
	}
	return UnquoteValid(), true
}

// UnquoteValid is Unquote of lit, which a scan found a JSON string.
func ( []byte) []byte {
	 := [1 : len()-1]
	 := bytes.IndexByte(, '\\')
	if  < 0 {
		if utf8.Valid() {
			return 
		}
		return AppendValidUTF8(make([]byte, 0, len()+2*utf8.UTFMax), )
	}
	// the closing quote of lit follows s, as UnescapeTo needs
	 := make([]byte, len())
	 = [:UnescapeTo(unsafe.Pointer(unsafe.SliceData()), , )]
	return ReplaceInvalidUTF8(, 0)
}

func isHex( byte) bool {
	return '0' <=  &&  <= '9' || 'a' <=  &&  <= 'f' || 'A' <=  &&  <= 'F'
}