package encoder
import (
"encoding/binary"
"reflect"
"unsafe"
"github.com/goccy/go-json/internal/runtime"
)
type MapLayout struct {
collect func (p unsafe .Pointer , c *MapContext )
StringKey bool
ScalarValue bool
InterfaceValue bool
ValueKind reflect .Kind
keySize uintptr
valueSize uintptr
Cyclic bool
}
const wordSize = unsafe .Sizeof (uintptr (0 ))
const mapValueWords = 32
func NewMapLayout (typ reflect .Type ) *MapLayout {
l := &MapLayout {
StringKey : typ .Key ().Kind () == reflect .String ,
keySize : rawKeySize (typ .Key ()),
valueSize : typ .Elem ().Size (),
ValueKind : typ .Elem ().Kind (),
Cyclic : reaches (typ .Key (), typ , map [reflect .Type ]bool {}) || reaches (typ .Elem (), typ , map [reflect .Type ]bool {}),
}
if collect := stringKeyCollector (l .valueSize ); l .StringKey && collect != nil {
l .collect = collect
l .InterfaceValue = typ .Elem ().Kind () == reflect .Interface && typ .Elem ().NumMethod () == 0
} else {
l .collect = withMethodValues (typ .Elem (), newReflectCollector (typ ))
}
return l
}
func stringKeyCollector(size uintptr ) func (unsafe .Pointer , *MapContext ) {
switch {
case size %wordSize == 0 && size /wordSize <= mapValueWords :
return stringKeyCollectors [size /wordSize ]
case size < uintptr (len (byteValueCollectors )):
return byteValueCollectors [size ]
}
return nil
}
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 ],
}
func rawKeySize(typ reflect .Type ) uintptr {
return max (typ .Size (), 1 )
}
func collectStringKeys[V any ](p unsafe .Pointer , c *MapContext ) {
for k , v := range *(*map [string ]V )(unsafe .Pointer (&p )) {
c .Keys = append (c .Keys , k )
c .Values = append (c .Values , unsafe .Slice ((*byte )(unsafe .Pointer (&v )), unsafe .Sizeof (v ))...)
}
}
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 ],
}
func newReflectCollector(typ reflect .Type ) func (unsafe .Pointer , *MapContext ) {
keyType , valueType := typ .Key (), typ .Elem ()
if keyType .Kind () == reflect .Interface {
return newInterfaceKeyCollector (typ )
}
stringKey := keyType .Kind () == reflect .String
keySize , valueSize := rawKeySize (keyType ), valueType .Size ()
keyDirect , valueDirect := !runtime .IfaceIndir (keyType ), !runtime .IfaceIndir (valueType )
valueIsIface := valueType .Kind () == reflect .Interface
typPtr := runtime .TypePtr (typ )
return func (p unsafe .Pointer , c *MapContext ) {
var mapIface any
*(*emptyInterface )(unsafe .Pointer (&mapIface )) = emptyInterface {typ : typPtr , ptr : p }
m := reflect .ValueOf (mapIface )
key := reflect .ValueOf (&c .keyIface ).Elem ()
value := reflect .ValueOf (&c .valueIface ).Elem ()
it := &c .iter
it .Reset (m )
for it .Next () {
key .SetIterKey (it )
value .SetIterValue (it )
k := ifaceData (&c .keyIface , keyDirect )
if stringKey {
c .Keys = append (c .Keys , *(*string )(k ))
} else {
c .RawKeys = append (c .RawKeys , unsafe .Slice ((*byte )(k ), keySize )...)
}
v := ifaceData (&c .valueIface , valueDirect )
if valueIsIface {
v = unsafe .Pointer (&c .valueIface )
}
c .Values = append (c .Values , unsafe .Slice ((*byte )(v ), valueSize )...)
}
it .Reset (reflect .Value {})
c .keyIface , c .valueIface = nil , nil
}
}
func withMethodValues(valueType reflect .Type , collect func (unsafe .Pointer , *MapContext )) func (unsafe .Pointer , *MapContext ) {
if valueType .Kind () != reflect .Interface || valueType .NumMethod () == 0 {
return collect
}
return func (p unsafe .Pointer , c *MapContext ) {
collect (p , c )
for i := 0 ; i < len (c .Values ); i += int (unsafe .Sizeof (any (nil ))) {
value := unsafe .Pointer (&c .Values [i ])
if v := *(*any )(value ); v != nil {
reflect .NewAt (valueType , value ).Elem ().Set (reflect .ValueOf (v ))
}
}
}
}
func newInterfaceKeyCollector(typ reflect .Type ) func (unsafe .Pointer , *MapContext ) {
valueType := typ .Elem ()
valueSize := valueType .Size ()
valueDirect := !runtime .IfaceIndir (valueType )
valueIsIface := valueType .Kind () == reflect .Interface
typPtr := runtime .TypePtr (typ )
return func (p unsafe .Pointer , c *MapContext ) {
var mapIface any
*(*emptyInterface )(unsafe .Pointer (&mapIface )) = emptyInterface {typ : typPtr , ptr : p }
m := reflect .ValueOf (mapIface )
key := reflect .ValueOf (&c .keyIface ).Elem ()
value := reflect .ValueOf (&c .valueIface ).Elem ()
it := &c .iter
it .Reset (m )
for it .Next () {
key .SetIterKey (it )
value .SetIterValue (it )
c .RawKeys = append (c .RawKeys , unsafe .Slice ((*byte )(unsafe .Pointer (&c .keyIface )), unsafe .Sizeof (c .keyIface ))...)
v := ifaceData (&c .valueIface , valueDirect )
if valueIsIface {
v = unsafe .Pointer (&c .valueIface )
}
c .Values = append (c .Values , unsafe .Slice ((*byte )(v ), valueSize )...)
}
it .Reset (reflect .Value {})
c .keyIface , c .valueIface = nil , nil
}
}
func ifaceData(iface *any , direct bool ) unsafe .Pointer {
data := &(*emptyInterface )(unsafe .Pointer (iface )).ptr
if direct {
return unsafe .Pointer (data )
}
return *data
}
func (l *MapLayout ) Reset (c *MapContext ) {
c .Keys , c .RawKeys , c .Values = c .Keys [:0 ], c .RawKeys [:0 ], c .Values [:0 ]
c .layout = l
}
func (l *MapLayout ) Collect (p unsafe .Pointer , c *MapContext ) int {
l .Reset (c )
l .collect (p , c )
if l .StringKey {
c .Len = len (c .Keys )
} else {
c .Len = len (c .RawKeys ) / int (l .keySize )
}
return c .Len
}
func MapLen (p unsafe .Pointer ) int {
return len (*(*map [struct {}]struct {})(unsafe .Pointer (&p )))
}
func (c *MapContext ) KeyAt (i int ) unsafe .Pointer {
if c .layout .StringKey {
return unsafe .Pointer (&c .Keys [i ])
}
return unsafe .Pointer (&c .RawKeys [uintptr (i )*c .layout .keySize ])
}
func (c *MapContext ) ValueAt (i int ) unsafe .Pointer {
if c .layout .valueSize == 0 {
return unsafe .Pointer (&c .Len )
}
return unsafe .Pointer (&c .Values [uintptr (i )*c .layout .valueSize ])
}
func (c *MapContext ) SortKeys () {
n := len (c .Keys )
if cap (c .Order ) < n {
c .Order = make ([]int32 , n )
c .prefixes = make ([]uint64 , n )
}
order , prefixes , keys := c .Order [:n ], c .prefixes [:n ], c .Keys
for i , key := range keys {
order [i ] = int32 (i )
prefixes [i ] = keyPrefix (key )
}
if n > maxItemsOfInsertionSort {
sortKeyOrder (order , prefixes , keys )
} else {
insertionSortKeyOrder (order , prefixes , keys )
}
c .Order = order
}
func keyLess(a , b int32 , prefixes []uint64 , keys []string ) bool {
if pa , pb := prefixes [a ], prefixes [b ]; pa != pb {
return pa < pb
}
return keys [a ] < keys [b ]
}
func sortKeyOrder(order []int32 , prefixes []uint64 , keys []string ) {
for len (order ) > maxItemsOfInsertionSort {
last := len (order ) - 1
mid := last / 2
if keyLess (order [mid ], order [0 ], prefixes , keys ) {
order [0 ], order [mid ] = order [mid ], order [0 ]
}
if keyLess (order [last ], order [mid ], prefixes , keys ) {
order [mid ], order [last ] = order [last ], order [mid ]
if keyLess (order [mid ], order [0 ], prefixes , keys ) {
order [0 ], order [mid ] = order [mid ], order [0 ]
}
}
pivot := order [mid ]
i , j := 0 , last
for {
for keyLess (order [i ], pivot , prefixes , keys ) {
i ++
}
for keyLess (pivot , order [j ], prefixes , keys ) {
j --
}
if i >= j {
break
}
order [i ], order [j ] = order [j ], order [i ]
i ++
j --
}
if j +1 < len (order )-j -1 {
sortKeyOrder (order [:j +1 ], prefixes , keys )
order = order [j +1 :]
} else {
sortKeyOrder (order [j +1 :], prefixes , keys )
order = order [:j +1 ]
}
}
insertionSortKeyOrder (order , prefixes , keys )
}
func insertionSortKeyOrder(order []int32 , prefixes []uint64 , keys []string ) {
for i := 1 ; i < len (order ); i ++ {
e := order [i ]
if !keyLess (e , order [i -1 ], prefixes , keys ) {
continue
}
j := i
for ; j > 0 && keyLess (e , order [j -1 ], prefixes , keys ); j -- {
order [j ] = order [j -1 ]
}
order [j ] = e
}
}
func keyPrefix(key string ) uint64 {
if len (key ) >= 8 {
return binary .BigEndian .Uint64 (unsafe .Slice (unsafe .StringData (key ), 8 ))
}
var b [8 ]byte
copy (b [:], key )
return binary .BigEndian .Uint64 (b [:])
}
func reaches(typ , target reflect .Type , seen map [reflect .Type ]bool ) bool {
if typ == target || typ .Kind () == reflect .Interface {
return true
}
if seen [typ ] {
return false
}
seen [typ ] = true
switch typ .Kind () {
case reflect .Pointer , reflect .Slice , reflect .Array :
return reaches (typ .Elem (), target , seen )
case reflect .Map :
return reaches (typ .Key (), target , seen ) || reaches (typ .Elem (), target , seen )
case reflect .Struct :
for i := range typ .NumField () {
if reaches (typ .Field (i ).Type , target , seen ) {
return true
}
}
}
return false
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .