package decoder

import (
	
	
	
)

const (
	lsb = 0x0101010101010101
	msb = 0x8080808080808080
	// bit5 is the bit which distinguishes '{' from '[' and '}' from ']'.
	bit5 = 0x2020202020202020

	// scanBlockSize is the number of the bytes the masks of a scan cover.
	scanBlockSize = 64
	// shortScanLength is the number of the bytes a scan looks at one by one before it works by blocks.
	shortScanLength = 16
)

// NewInput returns the buffer which the decoders decode: a copy of the input followed by a nul byte,
// which ends every scan.
func ( []byte) []byte {
	 := make([]byte, len()+1)
	copy(, )
	return 
}

// load64 returns the eight bytes at pos as a little-endian word, whatever the byte order of the machine:
// the masks made from a word give the position of a byte by the count of the trailing zeros.
// It compiles to a single load on a little-endian machine.
func load64( []byte,  int64) uint64 {
	return binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add((*sliceHeader)(unsafe.Pointer(&)).data, ))[:])
}

// byteMask returns the word whose byte is 0x80 where the byte of w is c, and 0 elsewhere.
func byteMask(,  uint64) uint64 {
	 :=  ^ ( * lsb)
	return ^((( & ^uint64(msb)) + ^uint64(msb)) | ) & msb
}

// scanMasks are the masks of a block of scanBlockSize bytes: bit i of a mask is set if the byte i
// of the block is the character. The brackets are folded: open is '{' or '[' and closing is '}' or ']'.
type scanMasks struct {
	quote     uint64
	backslash uint64
	open      uint64
	closing   uint64
}

// scanBlockWords computes the masks of the block at p by words, eight bytes at a time.
// It is what the architectures without a SIMD scan use.
func scanBlockWords( unsafe.Pointer,  *scanMasks) {
	var , , ,  uint64
	for  := 0;  < scanBlockSize/8; ++ {
		 := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(, *8))[:])
		 :=  &^ bit5
		 := uint( * 8)
		 |= gatherMask(byteMask(, '"')) << 
		 |= gatherMask(byteMask(, '\\')) << 
		 |= gatherMask(byteMask(, '[')) << 
		 |= gatherMask(byteMask(, ']')) << 
	}
	.quote, .backslash, .open, .closing = , , , 
}

// gatherMask turns a mask of 0x80 bytes into the byte whose bit i is the byte i of the mask.
func gatherMask( uint64) uint64 {
	return (( >> 7) * 0x0102040810204080) >> 56
}

// compoundScanner finds the end of an object or an array without decoding it: the position after
// the bracket which closes it. It keeps its state between the calls of scan, so that a stream may
// scan what it has read so far and go on after reading more.
//
// The bytes are scanned a block at a time, by their masks ( scanMasks ): the quotes which are not
// escaped toggle whether the bytes are inside a string, which a prefix xor of the quote mask tells
// for every byte at once, and the brackets outside strings count the depth. The bytes are looked at
// one by one only in a block where the value may end. The depth is not limited here: the decoding
// of the value checks it.
type compoundScanner struct {
	// depth is the number of the brackets opened but not closed.
	depth    int64
	inString bool
	// escaped is whether the next byte is escaped by the backslash before it.
	escaped bool
}

// scan scans buf[pos:lim] and returns the position after the bracket which closes the value, or,
// when the value doesn't end before lim, the position it stopped at and false.
// A whole block is read at once where the capacity of the buffer has room for it.
func ( *compoundScanner) ( []byte, ,  int64) (int64, bool) {
	const  = 0x5555555555555555
	// A short value ends within a few bytes, which are looked at one by one: that costs less
	// than the masks of a whole block.
	,  := .scanBytes(, , min(+shortScanLength, ))
	if  {
		return , 
	}
	 := .depth
	var ,  uint64
	if .inString {
		 = ^uint64(0)
	}
	if .escaped {
		 = 1
	}
	 := (*sliceHeader)(unsafe.Pointer(&)).data
	 := int64(cap())
	for  <  {
		if +scanBlockSize >  {
			// The buffer has no room for a block: its last bytes are looked at one by one.
			.depth, .inString, .escaped = ,  != 0,  != 0
			return .scanBytes(, , )
		}
		var  scanMasks
		scanBlock(unsafe.Add(, ), &)
		 :=  - 
		if  < scanBlockSize {
			 := uint64(1)<<uint() - 1
			.quote &= 
			.backslash &= 
			.open &= 
			.closing &= 
		}
		// escaped has the bytes which follow an odd number of backslashes. A backslash which is
		// itself escaped doesn't escape; a run of backslashes may go on in the next block ( the carry ).
		 := .backslash &^ 
		 := <<1 | 
		 :=  &^  &^ 
		,  := bits.Add64(, , 0)
		 := ( ^ ( << 1)) & 
		if  < scanBlockSize {
			// whether the byte at lim, which the next call scans first, is escaped
			 = ( >> uint()) & 1
		} else {
			 = 
		}
		// inside has the bytes which are inside a string after the byte itself is read:
		// the parity of the quotes up to the byte, flipped if the block begins inside a string.
		 := .quote &^ 
		 := 
		 ^=  << 1
		 ^=  << 2
		 ^=  << 4
		 ^=  << 8
		 ^=  << 16
		 ^=  << 32
		 ^= 
		 = uint64(int64() >> 63) // the state after the last byte, in every bit
		// An escaped byte is neither a quote nor a bracket, wherever it is.
		 := ^( | )
		 := .open & 
		 := .closing & 
		 := int64(bits.OnesCount64())
		 := int64(bits.OnesCount64())
		if  <  {
			// the value can't end in this block
			 +=  - 
			 += scanBlockSize
			continue
		}
		for  :=  | ;  != 0;  &=  - 1 {
			 := bits.TrailingZeros64()
			if &(1<<uint()) != 0 {
				++
			} else {
				--
				if  == 0 {
					return  + int64() + 1, true
				}
			}
		}
		 += scanBlockSize
	}
	.depth, .inString, .escaped = ,  != 0,  != 0
	return , false
}

// scanBytes scans buf[pos:end] one byte at a time, as scan does by blocks.
// A byte after a backslash is neither a quote nor a bracket, wherever it is.
func ( *compoundScanner) ( []byte, ,  int64) (int64, bool) {
	if  >=  {
		return , false
	}
	,  := .depth, .inString
	if .escaped {
		.escaped = false
		++
	}
	for  <  {
		if  {
			for  <  {
				 := []
				++
				if  == '"' {
					 = false
					break
				}
				if  == '\\' {
					++
				}
			}
			continue
		}
		 := []
		++
		switch  {
		case '"':
			 = true
		case '\\':
			++
		case '{', '[':
			++
		case '}', ']':
			--
			if  == 0 {
				return , true
			}
		}
	}
	// A backslash as the last byte escapes the byte after end.
	 :=  > 
	if  {
		 = 
	}
	.depth, .inString, .escaped = , , 
	return , false
}