package decoder

import (
	
	
	
	
	
)

// structKeys finds the field of a struct which an object key is decoded into, as encoding/json does:
// the field whose key is the same, or else the first field whose key is the same by case folding.
//
// The fields are in a table keyed by their folded keys: the fields of a folded key are in one entry, so that
// a key is looked up once, whether it matches a field exactly or by folding. A key is looked up by two words:
// its first eight bytes, and its last eight bytes, which overlap the first ones for a key shorter than 16 bytes.
// These are all the bytes of a key of up to 16 bytes, so such a key is compared by its length and the two words
// only; a longer one is compared by the words between them as well. The words of a key of ASCII are folded in
// place, eight bytes at a time, and only a key which is not ASCII is folded rune by rune.
type structKeys struct {
	entries []keyEntry
	shift   uint
	// lengths has the bit of the length of every folded key ( 63 for the longer keys ):
	// a key of another length matches no field, which is known without a lookup.
	lengths uint64
	// exact is a table of the keys which are not ASCII, by their bytes as they are ( see findExact ), and
	// exactLengths has the bit of the length of every such key, as lengths does for the folded keys.
	exact        []keyEntry
	exactShift   uint
	exactLengths uint64
	// foldRunes has a bit for every rune which is not ASCII and which folds to a rune of a folded key, by the
	// low byte of the rune ( see mayFold ).
	foldRunes [4]uint64
	// foldLeads has a bit for the first byte of the encoding of every rune of foldRunes ( see leadMayFold ).
	foldLeads [4]uint64
	// hasRuneError is set if a key has utf8.RuneError, which a byte of an object key which is not valid UTF-8
	// is replaced by.
	hasRuneError bool
}

type keyEntry struct {
	// short is the word of the folded key if it is of less than 8 bytes, none of which is nul, and its field
	// is the only one: a short key of ASCII whose folded word is the same is of that field, whatever its case.
	// It is noShortKey for any other entry, which no such word is.
	short uint64
	// w0 and w1 are the words of the folded key, and n its length.
	w0, w1 uint64
	n      int
	folded []byte
	// unique is the field of the folded key if it is the only one, which a key matches whichever its case.
	unique *structFieldSet
	// fields are the fields of the folded key in the order of the struct: the first one is the field of
	// a key which matches none of them exactly.
	fields []*structFieldSet
}

// hasLength reports whether a key of n bytes may match a field.
func ( *structKeys) ( int) bool {
	return .lengths&(1<<(uint(min(, 63))&63)) != 0
}

// newStructKeys makes the table of the fields, which are in the order of the struct.
func newStructKeys( []*structFieldSet) *structKeys {
	// the table is at most half full, so that a lookup ends after a few entries.
	 := 8
	for  < 2*len() {
		 *= 2
	}
	 := &structKeys{
		entries: make([]keyEntry, ),
		shift:   uint(64 - bits.TrailingZeros(uint())),
	}
	for ,  := range  {
		 := appendFoldedKey(nil, []byte(.key))
		if  := .find();  != nil {
			.fields = append(.fields, )
			.unique = nil
			continue
		}
		.insert(, )
	}
	.makeExact(, false)
	.makeFoldRunes()
	for  := range .entries {
		 := &.entries[]
		.short = noShortKey
		if .unique != nil && .n < 8 && !bytes.Contains(.folded, []byte{0}) {
			.short = .w0
		}
	}
	return 
}

// makeExact makes the table of the keys which are not ASCII, or of all the keys if all is set ( for v2, which
// matches names as they are ), by their bytes as they are. A key which is not valid UTF-8 is not in it: an object
// key which is not valid UTF-8 is decoded with its bytes replaced first.
func ( *structKeys) ( []*structFieldSet,  bool) {
	var  []*structFieldSet
	for ,  := range  {
		if ( || !isASCII(.key)) && utf8.ValidString(.key) {
			 = append(, )
		}
	}
	if len() == 0 {
		return
	}
	 := 8
	for  < 2*len() {
		 *= 2
	}
	.exact = make([]keyEntry, )
	.exactShift = uint(64 - bits.TrailingZeros(uint()))
	for ,  := range  {
		 := []byte(.key)
		,  := keyWords()
		,  := hashWords(, , len())
		 := len(.exact) - 1
		for  := indexOf(, , .exactShift); ;  = ( + 1) &  {
			if .exact[].unique == nil {
				.exact[] = keyEntry{w0: , w1: , n: len(), folded: , unique: }
				.exactLengths |= 1 << (uint(min(len(), 63)) & 63)
				break
			}
		}
	}
}

// findExact returns the field whose key is the same as the key, which is not ASCII and is in a buffer which
// has room for a word after it, or nil. w0 and w1 are the words of the key as keyWords makes them.
func ( *structKeys) ( []byte, ,  uint64) *structFieldSet {
	 := len()
	 := len(.exact) - 1
	,  := hashWords(, , )
	for  := indexOf(, , .exactShift); ;  = ( + 1) &  {
		 := &.exact[]
		if .unique == nil {
			return nil
		}
		if .n ==  && .w0 ==  && .w1 ==  && ( <= 16 || equalMiddleWords(, .folded)) {
			return .unique
		}
	}
}

// hasExactLength reports whether a key of n bytes which is not ASCII may be the same as the key of a field.
func ( *structKeys) ( int) bool {
	return .exactLengths&(1<<(uint(min(, 63))&63)) != 0
}

// equalMiddleWords reports whether two keys of the same length of more than 16 bytes, whose first and last eight
// bytes are known to be the same, have the same words between them.
func equalMiddleWords(,  []byte) bool {
	 := len()
	if  != len() {
		return false
	}
	for  := 8;  < -8;  += 8 {
		if binary.LittleEndian.Uint64([:]) != binary.LittleEndian.Uint64([:]) {
			return false
		}
	}
	return true
}

// makeFoldRunes sets the bits of the runes which are not ASCII and fold to a rune of a key: the runes of the
// fold orbits of the runes of the keys, which include the Kelvin sign for K and the long s for S.
func ( *structKeys) ( []*structFieldSet) {
	for ,  := range  {
		for ,  := range .key {
			if  == utf8.RuneError {
				.hasRuneError = true
			}
			for  := ; ; {
				if  >= utf8.RuneSelf {
					.foldRunes[&0xff>>6] |= 1 << (uint() & 63)
					 := utf8.AppendRune(nil, )[0]
					.foldLeads[>>6] |= 1 << ( & 63)
				}
				if  = unicode.SimpleFold();  ==  {
					break
				}
			}
		}
	}
}

// mayFold reports whether a key which is not ASCII may be of a field by case folding: every rune of it which
// is not ASCII folds to a rune of a key, which is told by the low byte of the rune. The low byte is taken from
// the last two bytes of the encoding of the rune, which is not decoded. A key which is not valid UTF-8 has its
// invalid bytes replaced by utf8.RuneError, so it may be of a field only if a key has utf8.RuneError: then
// the runes are decoded.
func ( *structKeys) ( []byte) bool {
	if .hasRuneError {
		return .mayFoldDecoded()
	}
	 := len()
	for  := 0;  < ; {
		 := []
		if  < utf8.RuneSelf {
			++
			continue
		}
		 := 2
		switch {
		case  < 0xc0:
			return false // a continuation byte without a first byte: not valid UTF-8
		case  >= 0xf0:
			 = 4
		case  >= 0xe0:
			 = 3
		}
		if + >  {
			return false
		}
		 := [+-2]&3<<6 | [+-1]&0x3f
		if .foldRunes[>>6]&(1<<(&63)) == 0 {
			return false
		}
		 += 
	}
	return true
}

// leadMayFold reports whether the first byte of the key which is not ASCII, if it is in the first word of the
// key, w0, may be the first byte of a rune which folds to a rune of a key, and else true. It is the cheapest
// check, which needs no load: most keys which are of no field are told so by it.
func ( *structKeys) ( uint64) bool {
	 :=  & msb
	if  == 0 || .hasRuneError {
		return true
	}
	 := byte( >> (uint(bits.TrailingZeros64()) - 7))
	return .foldLeads[>>6]&(1<<(&63)) != 0
}

// firstRuneMayFold reports whether the first rune of the key which is not ASCII may fold to a rune of a key, if
// that rune begins in the first word of the key, w0, and else true: it tells mayFold for most keys, without a
// call. The low byte of the rune is taken from its bytes as mayFold does, and a key which may not be valid
// UTF-8 is left to mayFold.
func ( *structKeys) ( []byte,  uint64) bool {
	 :=  & msb
	if  == 0 || .hasRuneError {
		return true
	}
	 := bits.TrailingZeros64() / 8
	 := []
	 := 2
	switch {
	case  < 0xc0:
		return true
	case  >= 0xf0:
		 = 4
	case  >= 0xe0:
		 = 3
	}
	if + > len() {
		return true
	}
	 := [+-2]&3<<6 | [+-1]&0x3f
	return .foldRunes[>>6]&(1<<(&63)) != 0
}

// mayFoldDecoded is mayFold by the decoded runes.
func ( *structKeys) ( []byte) bool {
	for  := 0;  < len(); {
		if [] < utf8.RuneSelf {
			++
			continue
		}
		,  := utf8.DecodeRune([:])
		if .foldRunes[&0xff>>6]&(1<<(uint()&63)) == 0 {
			return false
		}
		 += 
	}
	return true
}

func isASCII( string) bool {
	for  := 0;  < len(); ++ {
		if [] >= utf8.RuneSelf {
			return false
		}
	}
	return true
}

// noShortKey is the short word of an entry which a short key is not found by: a word of ASCII has no byte of
// 0x80 or more.
const noShortKey = ^uint64(0)

// keyWords returns the words of a key: its first eight bytes and its last eight bytes, as little-endian
// numbers, which are zero where the key is shorter. The capacity of the key is read past its length when it
// has room, which is the rest of the buffer of the input.
func keyWords( []byte) (uint64, uint64) {
	 := len()
	switch {
	case  >= 8:
		return binary.LittleEndian.Uint64(), binary.LittleEndian.Uint64([-8:])
	case cap() >= 8:
		return binary.LittleEndian.Uint64([:8]) & (1<<(8*uint()) - 1), 0
	}
	var  uint64
	for  :=  - 1;  >= 0; -- {
		 = <<8 | uint64([])
	}
	return , 0
}

// index returns the first entry to look at for a key whose words are w0 and w1, with the bit 5 of their bytes
// set by hashWords: a letter of either case has the same index, so the index of a key is made from its bytes
// before they are folded. The product spreads the keys, which differ in a few bits.
func ( *structKeys) (,  uint64) int {
	return indexOf(, , .shift)
}

func indexOf(,  uint64,  uint) int {
	 := ( ^ bits.RotateLeft64(, 29)) * 0x9E3779B97F4A7C15
	return int( >> )
}

// hashWords returns the words of a key of n bytes, or of its folded key, which index takes: the bit 5 of their
// bytes set, which folding a letter doesn't change, and the bytes after the key zero.
func hashWords(,  uint64,  int) (uint64, uint64) {
	if  < 8 {
		return ( | bit5) & (1<<(uint()*8&63) - 1), 0
	}
	return  | bit5,  | bit5
}

func ( *structKeys) ( []byte,  *structFieldSet) {
	,  := keyWords()
	 := len(.entries) - 1
	for  := .index(hashWords(, , len())); ;  = ( + 1) &  {
		if .entries[].fields == nil {
			.entries[] = keyEntry{w0: , w1: , n: len(), folded: , unique: , fields: []*structFieldSet{}}
			.lengths |= 1 << uint(min(len(), 63))
			return
		}
	}
}

// find returns the entry of the folded key, or nil.
func ( *structKeys) ( []byte) *keyEntry {
	,  := keyWords()
	 := len()
	 := len(.entries) - 1
	for  := .index(hashWords(, , )); ;  = ( + 1) &  {
		 := &.entries[]
		if .fields == nil {
			return nil
		}
		if .n ==  && .w0 ==  && .w1 ==  && ( <= 16 || string(.folded) == string()) {
			return 
		}
	}
}

// field returns the field of the key among the fields of its folded key: the one whose key is the same,
// or the first one.
func ( *keyEntry) ( []byte) *structFieldSet {
	if len(.fields) == 1 {
		return .fields[0]
	}
	for ,  := range .fields {
		if .key == string() {
			return 
		}
	}
	return .fields[0]
}

// findASCII returns the field of a key of ASCII without an escape, whose words are w0 and w1, or nil.
func ( *structKeys) ( []byte, ,  uint64) *structFieldSet {
	 := len()
	 := .index(hashWords(, , ))
	,  = foldASCIIWord(), foldASCIIWord()
	 := len(.entries) - 1
	for  := ; ;  = ( + 1) &  {
		 := &.entries[]
		if .fields == nil {
			return nil
		}
		if .n ==  && .w0 ==  && .w1 ==  && ( <= 16 || equalFoldedASCII(, .folded)) {
			if len(.fields) == 1 {
				return .fields[0]
			}
			return .field()
		}
	}
}

// foldASCIIWord folds the bytes of a word of ASCII as encoding/json does: a lower case letter to upper case.
func foldASCIIWord( uint64) uint64 {
	// the bytes are less than 0x80: adding to one never carries to the next.
	 :=  + (0x80-'a')*lsb   // 0x80 in the bytes from 'a'
	 :=  + (0x80-'z'-1)*lsb // 0x80 in the bytes after 'z'
	 := ( &^ ) & msb  // 0x80 in the lower case letters
	return  &^ ( >> 2)   // clear 0x20 of them
}

// equalFoldedASCII reports whether the key of ASCII, of more than 16 bytes, folds to folded, whose first and
// last eight bytes are known to be the ones of the key folded: the words between them are compared.
func equalFoldedASCII(,  []byte) bool {
	 := len()
	if  != len() {
		return false
	}
	for  := 8;  < -8;  += 8 {
		if foldASCIIWord(binary.LittleEndian.Uint64([:])) != binary.LittleEndian.Uint64([:]) {
			return false
		}
	}
	return true
}

// lookup returns the field of the key, or nil, and the key, which is decoded in place if it is escaped.
func ( *structKeys) ( []byte,  stringInfo) (*structFieldSet, []byte) {
	if .firstEscape < 0 && !.nonASCII {
		if !.hasLength(len()) {
			return nil, 
		}
		,  := keyWords()
		return .findASCII(, , ), 
	}
	 = decodeLiteral(, )
	var  [64]byte
	if  := .find(appendFoldedKey([:0], ));  != nil {
		return .field(), 
	}
	return nil, 
}

// appendFoldedKey appends the key folded as encoding/json folds a key to compare it case insensitively:
// a lower case ASCII letter to upper case, and any other rune to the smallest rune which folds to it.
func appendFoldedKey(,  []byte) []byte {
	for  := 0;  < len(); {
		if  := [];  < utf8.RuneSelf {
			if 'a' <=  &&  <= 'z' {
				 -= 'a' - 'A'
			}
			 = append(, )
			++
			continue
		}
		,  := utf8.DecodeRune([:])
		 = utf8.AppendRune(, foldRune())
		 += 
	}
	return 
}

// foldRune returns the smallest rune of the fold set of r.
func foldRune( rune) rune {
	for {
		 := unicode.SimpleFold()
		if  <=  {
			return 
		}
		 = 
	}
}