package encoder

import (
	
	
	

	
)

// The entries of a map are read into the map context before they are encoded: the keys and the values are
// copied, so that the VM encodes them from the context, in the order of the map or sorted by the keys.
//
// The runtime has no public function which gives the entries of a map of a type known only at run time
// without an allocation: reflect.MapIter copies a key and a value with a call of ten nanoseconds each, and
// go-json read them through linknames of the runtime for years. Instead, a map with keys of a string kind is
// ranged over as a map of the same layout: the layout of a map depends only on the size and the alignment of
// the key and of the value, and the hash depends only on the key. So map[K]V, with K of a string kind, is
// read as a map[string] of a value of the size of V ( see stringKeyCollector ) by the code the compiler makes
// for a range: no allocation, no call for an entry, and no dependence on the runtime beyond the layout of a
// map being what its type says. A map of another key, or of a value of another size, is read by
// reflect.MapIter, which is slower but is the public way.

// MapLayout is how the VM reads the entries of a map of a type, decided when the type is compiled.
type MapLayout struct {
	// collect reads the entries of the map at p into the context.
	collect func(p unsafe.Pointer, c *MapContext)
	// StringKey is whether the keys are of a string kind: then they are in MapContext.Keys.
	StringKey bool
	// A map whose entries are not sorted is written by the VM as it reads the map, when its keys are of a
	// string kind and the values are written by one opcode of a scalar ( ScalarValue: the map is ranged over
	// as a map of the values of the basic type of ValueKind, appendMapScalarValues ), or when the values are of
	// interface{}, the map of a JSON object as a value of interface{} ( InterfaceValue: the values which hold a
	// scalar are written, and the others are read into the context, appendMapAsRead ).
	ScalarValue    bool
	InterfaceValue bool
	// ValueKind is the kind of the values.
	ValueKind reflect.Kind
	keySize   uintptr
	valueSize uintptr
	// Cyclic is whether an entry may hold the map again, which is recorded for the detection of cycles then ( see
	// RuntimeContext.RecordMap ): the type of a key or a value reaches the type of the map, or an interface.
	Cyclic bool
}

// wordSize is the size of a word, of a pointer, by which a value is read when its size is a multiple of it.
const wordSize = unsafe.Sizeof(uintptr(0))

// mapValueWords is the number of the words of a value up to which a map is ranged over as a map of the same
// layout: 256 bytes on 64-bit platforms and 128 bytes on 32-bit ones. A value of more than 128 bytes is stored
// out of the map by the runtime, but so is the value of the map[string][n]uintptr of its size, so the layouts
// are still the same. Each size is a function of about a kilobyte of code, so the sizes stop there; a larger
// value is read by reflect.
const mapValueWords = 32

// NewMapLayout returns how the VM reads a map of the type.
func ( reflect.Type) *MapLayout {
	 := &MapLayout{
		StringKey: .Key().Kind() == reflect.String,
		keySize:   rawKeySize(.Key()),
		valueSize: .Elem().Size(),
		ValueKind: .Elem().Kind(),
		Cyclic:    reaches(.Key(), , map[reflect.Type]bool{}) || reaches(.Elem(), , map[reflect.Type]bool{}),
	}
	if  := stringKeyCollector(.valueSize); .StringKey &&  != nil {
		.collect = 
		.InterfaceValue = .Elem().Kind() == reflect.Interface && .Elem().NumMethod() == 0
	} else {
		.collect = withMethodValues(.Elem(), newReflectCollector())
	}
	return 
}

// stringKeyCollector returns the function which reads a map with keys of a string kind and values of size bytes
// as a map of a value of the same size, or nil when there is none. A value of a size and of an alignment up to
// the ones of the key is at the same place in a map of every layout ( the Swiss tables of Go 1.24, the split
// groups of Go 1.28, the buckets before ), whatever its type.
func stringKeyCollector( uintptr) func(unsafe.Pointer, *MapContext) {
	switch {
	case %wordSize == 0 && /wordSize <= mapValueWords:
		return stringKeyCollectors[/wordSize]
	case  < uintptr(len(byteValueCollectors)):
		return byteValueCollectors[]
	}
	return nil
}

// byteValueCollectors are the functions which read a map with keys of a string kind, by the bytes of a value
// smaller than 32 bytes whose size is not a multiple of a word ( see stringKeyCollectors ): the sizes which are
// multiples of 8 bytes are left out, as they are of words on every platform.
var byteValueCollectors = [32]func(unsafe.Pointer, *MapContext){
	1:  collectStringKeys[[1]byte],
	2:  collectStringKeys[[2]byte],
	3:  collectStringKeys[[3]byte],
	4:  collectStringKeys[[4]byte],
	5:  collectStringKeys[[5]byte],
	6:  collectStringKeys[[6]byte],
	7:  collectStringKeys[[7]byte],
	9:  collectStringKeys[[9]byte],
	10: collectStringKeys[[10]byte],
	11: collectStringKeys[[11]byte],
	12: collectStringKeys[[12]byte],
	13: collectStringKeys[[13]byte],
	14: collectStringKeys[[14]byte],
	15: collectStringKeys[[15]byte],
	17: collectStringKeys[[17]byte],
	18: collectStringKeys[[18]byte],
	19: collectStringKeys[[19]byte],
	20: collectStringKeys[[20]byte],
	21: collectStringKeys[[21]byte],
	22: collectStringKeys[[22]byte],
	23: collectStringKeys[[23]byte],
	25: collectStringKeys[[25]byte],
	26: collectStringKeys[[26]byte],
	27: collectStringKeys[[27]byte],
	28: collectStringKeys[[28]byte],
	29: collectStringKeys[[29]byte],
	30: collectStringKeys[[30]byte],
	31: collectStringKeys[[31]byte],
}

// rawKeySize is the number of the bytes of RawKeys which a key of typ takes: its size, or one byte for a key of
// no size, so that a map of it has as many keys in RawKeys as it has. The byte is never used: such a key is read at
// its address only.
func rawKeySize( reflect.Type) uintptr {
	return max(.Size(), 1)
}

// collectStringKeys reads the map at p, as a map[string]V, into the context.
func collectStringKeys[ any]( unsafe.Pointer,  *MapContext) {
	for ,  := range *(*map[string])(unsafe.Pointer(&)) {
		.Keys = append(.Keys, )
		.Values = append(.Values, unsafe.Slice((*byte)(unsafe.Pointer(&)), unsafe.Sizeof())...)
	}
}

// stringKeyCollectors are the functions which read a map with keys of a string kind, by the words of a value.
var stringKeyCollectors = [mapValueWords + 1]func(unsafe.Pointer, *MapContext){
	collectStringKeys[[0]uintptr],
	collectStringKeys[[1]uintptr],
	collectStringKeys[[2]uintptr],
	collectStringKeys[[3]uintptr],
	collectStringKeys[[4]uintptr],
	collectStringKeys[[5]uintptr],
	collectStringKeys[[6]uintptr],
	collectStringKeys[[7]uintptr],
	collectStringKeys[[8]uintptr],
	collectStringKeys[[9]uintptr],
	collectStringKeys[[10]uintptr],
	collectStringKeys[[11]uintptr],
	collectStringKeys[[12]uintptr],
	collectStringKeys[[13]uintptr],
	collectStringKeys[[14]uintptr],
	collectStringKeys[[15]uintptr],
	collectStringKeys[[16]uintptr],
	collectStringKeys[[17]uintptr],
	collectStringKeys[[18]uintptr],
	collectStringKeys[[19]uintptr],
	collectStringKeys[[20]uintptr],
	collectStringKeys[[21]uintptr],
	collectStringKeys[[22]uintptr],
	collectStringKeys[[23]uintptr],
	collectStringKeys[[24]uintptr],
	collectStringKeys[[25]uintptr],
	collectStringKeys[[26]uintptr],
	collectStringKeys[[27]uintptr],
	collectStringKeys[[28]uintptr],
	collectStringKeys[[29]uintptr],
	collectStringKeys[[30]uintptr],
	collectStringKeys[[31]uintptr],
	collectStringKeys[[32]uintptr],
}

// newReflectCollector returns the function which reads a map of the type by reflect.MapIter: the key and the
// value of an entry are set to interface values, which then refer to them in the map, or hold them if they
// are of a pointer shape, without an allocation.
func newReflectCollector( reflect.Type) func(unsafe.Pointer, *MapContext) {
	,  := .Key(), .Elem()
	if .Kind() == reflect.Interface {
		return newInterfaceKeyCollector()
	}
	 := .Kind() == reflect.String
	,  := rawKeySize(), .Size()
	,  := !runtime.IfaceIndir(), !runtime.IfaceIndir()
	// a value which is an interface value is copied to the interface value as it is: the value is the words.
	 := .Kind() == reflect.Interface
	 := runtime.TypePtr()
	return func( unsafe.Pointer,  *MapContext) {
		// the map as a value which is not addressable: SetIterKey copies the key of an addressable map.
		var  any
		*(*emptyInterface)(unsafe.Pointer(&)) = emptyInterface{typ: , ptr: }
		 := reflect.ValueOf()
		 := reflect.ValueOf(&.keyIface).Elem()
		 := reflect.ValueOf(&.valueIface).Elem()
		 := &.iter
		.Reset()
		for .Next() {
			.SetIterKey()
			.SetIterValue()
			 := ifaceData(&.keyIface, )
			if  {
				.Keys = append(.Keys, *(*string)())
			} else {
				.RawKeys = append(.RawKeys, unsafe.Slice((*byte)(), )...)
			}
			 := ifaceData(&.valueIface, )
			if  {
				 = unsafe.Pointer(&.valueIface)
			}
			.Values = append(.Values, unsafe.Slice((*byte)(), )...)
		}
		.Reset(reflect.Value{})
		.keyIface, .valueIface = nil, nil
	}
}

// withMethodValues returns collect, which reads the values as the words of an interface{}, for values of valueType,
// with the values made the words of valueType when it is an interface type with methods: an interface{} has the
// type of the value where such a type has its itab.
func withMethodValues( reflect.Type,  func(unsafe.Pointer, *MapContext)) func(unsafe.Pointer, *MapContext) {
	if .Kind() != reflect.Interface || .NumMethod() == 0 {
		return 
	}
	return func( unsafe.Pointer,  *MapContext) {
		(, )
		for  := 0;  < len(.Values);  += int(unsafe.Sizeof(any(nil))) {
			 := unsafe.Pointer(&.Values[])
			if  := *(*any)();  != nil {
				reflect.NewAt(, ).Elem().Set(reflect.ValueOf())
			}
		}
	}
}

// newInterfaceKeyCollector is newReflectCollector for a map whose keys are of an interface type: a key is the
// words of the interface{} it is set to, whatever its interface type is ( see appendInterfaceMapKey ).
func newInterfaceKeyCollector( reflect.Type) func(unsafe.Pointer, *MapContext) {
	 := .Elem()
	 := .Size()
	 := !runtime.IfaceIndir()
	 := .Kind() == reflect.Interface
	 := runtime.TypePtr()
	return func( unsafe.Pointer,  *MapContext) {
		var  any
		*(*emptyInterface)(unsafe.Pointer(&)) = emptyInterface{typ: , ptr: }
		 := reflect.ValueOf()
		 := reflect.ValueOf(&.keyIface).Elem()
		 := reflect.ValueOf(&.valueIface).Elem()
		 := &.iter
		.Reset()
		for .Next() {
			.SetIterKey()
			.SetIterValue()
			.RawKeys = append(.RawKeys, unsafe.Slice((*byte)(unsafe.Pointer(&.keyIface)), unsafe.Sizeof(.keyIface))...)
			 := ifaceData(&.valueIface, )
			if  {
				 = unsafe.Pointer(&.valueIface)
			}
			.Values = append(.Values, unsafe.Slice((*byte)(), )...)
		}
		.Reset(reflect.Value{})
		.keyIface, .valueIface = nil, nil
	}
}

// ifaceData returns the address of the value held by the interface value: the data word if the value is stored
// in it, which is the case for a value of a pointer shape, or what the data word points to.
func ifaceData( *any,  bool) unsafe.Pointer {
	 := &(*emptyInterface)(unsafe.Pointer()).ptr
	if  {
		return unsafe.Pointer()
	}
	return *
}

// Reset empties the context for the entries of a map of the layout.
func ( *MapLayout) ( *MapContext) {
	.Keys, .RawKeys, .Values = .Keys[:0], .RawKeys[:0], .Values[:0]
	.layout = 
}

// Collect reads the entries of the map at p into the context, and returns their number.
func ( *MapLayout) ( unsafe.Pointer,  *MapContext) int {
	.Reset()
	.collect(, )
	if .StringKey {
		.Len = len(.Keys)
	} else {
		.Len = len(.RawKeys) / int(.keySize)
	}
	return .Len
}

// MapLen returns the number of the entries of the map at p. The length of a map is in its header, whatever
// its type, so the map is read as one of any type.
func ( unsafe.Pointer) int {
	return len(*(*map[struct{}]struct{})(unsafe.Pointer(&)))
}

// KeyAt returns the address of the key of the entry: the string in Keys, or the bytes in RawKeys.
func ( *MapContext) ( int) unsafe.Pointer {
	if .layout.StringKey {
		return unsafe.Pointer(&.Keys[])
	}
	return unsafe.Pointer(&.RawKeys[uintptr()*.layout.keySize])
}

// ValueAt returns the address of the value of the entry. A value of no size has an address all the same: the
// opcode of a struct takes a nil one for a nil pointer.
func ( *MapContext) ( int) unsafe.Pointer {
	if .layout.valueSize == 0 {
		return unsafe.Pointer(&.Len)
	}
	return unsafe.Pointer(&.Values[uintptr()*.layout.valueSize])
}

// SortKeys sorts the entries by their keys, which are strings, as encoding/json does: Order is the entries in
// that order.
//
// A comparison of two keys is by their first eight bytes as one number first, which decides it for most of
// the keys of a JSON object, and by the strings only when those are the same: a comparison of strings is a
// call which costs more than the rest of a sort of a small map. The sort is written here, so that the
// comparisons are inlined into it: a sort which takes the comparison as a function, as slices.SortFunc does,
// calls it for every one.
func ( *MapContext) () {
	 := len(.Keys)
	if cap(.Order) <  {
		.Order = make([]int32, )
		.prefixes = make([]uint64, )
	}
	, ,  := .Order[:], .prefixes[:], .Keys
	for ,  := range  {
		[] = int32()
		[] = keyPrefix()
	}
	if  > maxItemsOfInsertionSort {
		sortKeyOrder(, , )
	} else {
		insertionSortKeyOrder(, , )
	}
	.Order = 
}

// keyLess is whether the key of the entry a comes before the one of b.
func keyLess(,  int32,  []uint64,  []string) bool {
	if ,  := [], [];  !=  {
		return  < 
	}
	return [] < []
}

// sortKeyOrder sorts the entries of order by their keys: by quicksort, with the median of three entries as the
// pivot, down to the parts of up to maxItemsOfInsertionSort entries, which are sorted by insertion. The smaller
// part is sorted first, and the larger one by the loop, so that the depth is logarithmic.
func sortKeyOrder( []int32,  []uint64,  []string) {
	for len() > maxItemsOfInsertionSort {
		 := len() - 1
		 :=  / 2
		// the median of the first, the middle and the last entries, at the middle
		if keyLess([], [0], , ) {
			[0], [] = [], [0]
		}
		if keyLess([], [], , ) {
			[], [] = [], []
			if keyLess([], [0], , ) {
				[0], [] = [], [0]
			}
		}
		 := []
		// Hoare's partition: the keys are distinct, so an entry equals the pivot only if it is the pivot.
		,  := 0, 
		for {
			for keyLess([], , , ) {
				++
			}
			for keyLess(, [], , ) {
				--
			}
			if  >=  {
				break
			}
			[], [] = [], []
			++
			--
		}
		if +1 < len()--1 {
			([:+1], , )
			 = [+1:]
		} else {
			([+1:], , )
			 = [:+1]
		}
	}
	insertionSortKeyOrder(, , )
}

// insertionSortKeyOrder sorts the entries of order by their keys by insertion, which is the fastest sort of a few
// entries.
func insertionSortKeyOrder( []int32,  []uint64,  []string) {
	for  := 1;  < len(); ++ {
		 := []
		if !keyLess(, [-1], , ) {
			continue
		}
		 := 
		for ;  > 0 && keyLess(, [-1], , ); -- {
			[] = [-1]
		}
		[] = 
	}
}

// keyPrefix returns the first eight bytes of the key as a number which compares as the bytes do, with zeros
// after a shorter key: a shorter key compares as less, as it should, unless the other has zeros there, and then
// the strings are compared.
func keyPrefix( string) uint64 {
	if len() >= 8 {
		return binary.BigEndian.Uint64(unsafe.Slice(unsafe.StringData(), 8))
	}
	var  [8]byte
	copy([:], )
	return binary.BigEndian.Uint64([:])
}

// reaches reports whether a value of typ may hold a value of target: typ is target, or an interface, or has one of
// them through its pointers, elements, keys and fields. seen are the types walked, which a recursive type reaches
// again.
func reaches(,  reflect.Type,  map[reflect.Type]bool) bool {
	if  ==  || .Kind() == reflect.Interface {
		return true
	}
	if [] {
		return false
	}
	[] = true
	switch .Kind() {
	case reflect.Pointer, reflect.Slice, reflect.Array:
		return (.Elem(), , )
	case reflect.Map:
		return (.Key(), , ) || (.Elem(), , )
	case reflect.Struct:
		for  := range .NumField() {
			if (.Field().Type, , ) {
				return true
			}
		}
	}
	return false
}