go-json/internal/encoder/compiler_race.go

71 lines
1.9 KiB
Go
Raw Normal View History

2021-11-22 07:20:03 +03:00
//go:build race
// +build race
package encoder
import (
"sync"
"unsafe"
"github.com/goccy/go-json/internal/runtime"
)
var setsMu sync.RWMutex
func CompileToGetCodeSet(typeptr uintptr) (*OpcodeSet, error) {
2021-03-16 18:22:19 +03:00
if typeptr > typeAddr.MaxTypeAddr {
return compileToGetCodeSetSlowPath(typeptr)
}
index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift
setsMu.RLock()
if codeSet := cachedOpcodeSets[index]; codeSet != nil {
setsMu.RUnlock()
return codeSet, nil
}
setsMu.RUnlock()
// noescape trick for header.typ ( reflect.*rtype )
copiedType := *(**runtime.Type)(unsafe.Pointer(&typeptr))
2021-11-27 13:34:06 +03:00
noescapeKeyCode, err := compile(&compileContext{
typ: copiedType,
structTypeToCode: map[uintptr]*StructCode{},
structTypeToCodes: map[uintptr]Opcodes{},
recursiveCodes: &Opcodes{},
})
if err != nil {
return nil, err
}
2021-11-27 13:34:06 +03:00
escapeKeyCode, err := compile(&compileContext{
typ: copiedType,
structTypeToCode: map[uintptr]*StructCode{},
structTypeToCodes: map[uintptr]Opcodes{},
recursiveCodes: &Opcodes{},
escapeKey: true,
})
if err != nil {
return nil, err
}
noescapeKeyCode = copyOpcode(noescapeKeyCode)
escapeKeyCode = copyOpcode(escapeKeyCode)
2021-06-25 14:17:12 +03:00
setTotalLengthToInterfaceOp(noescapeKeyCode)
setTotalLengthToInterfaceOp(escapeKeyCode)
interfaceNoescapeKeyCode := copyToInterfaceOpcode(noescapeKeyCode)
interfaceEscapeKeyCode := copyToInterfaceOpcode(escapeKeyCode)
codeLength := noescapeKeyCode.TotalLength()
2021-03-16 18:22:19 +03:00
codeSet := &OpcodeSet{
2021-06-25 14:17:12 +03:00
Type: copiedType,
NoescapeKeyCode: noescapeKeyCode,
EscapeKeyCode: escapeKeyCode,
InterfaceNoescapeKeyCode: interfaceNoescapeKeyCode,
InterfaceEscapeKeyCode: interfaceEscapeKeyCode,
CodeLength: codeLength,
EndCode: ToEndCode(interfaceNoescapeKeyCode),
}
setsMu.Lock()
cachedOpcodeSets[index] = codeSet
setsMu.Unlock()
return codeSet, nil
}