go-json/internal/encoder/compiler_race.go

47 lines
979 B
Go
Raw Normal View History

// +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)
}
2021-03-16 18:22:19 +03:00
index := typeptr - typeAddr.BaseTypeAddr
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))
code, err := compileHead(&compileContext{
typ: copiedType,
structTypeToCompiledCode: map[uintptr]*CompiledCode{},
})
if err != nil {
return nil, err
}
code = copyOpcode(code)
codeLength := code.TotalLength()
2021-03-16 18:22:19 +03:00
codeSet := &OpcodeSet{
Code: code,
CodeLength: codeLength,
}
setsMu.Lock()
cachedOpcodeSets[index] = codeSet
setsMu.Unlock()
return codeSet, nil
}