forked from mirror/go-json
47 lines
961 B
Go
47 lines
961 B
Go
|
// +build race
|
||
|
|
||
|
package encoder
|
||
|
|
||
|
import (
|
||
|
"sync"
|
||
|
"unsafe"
|
||
|
|
||
|
"github.com/goccy/go-json/internal/runtime"
|
||
|
)
|
||
|
|
||
|
var setsMu sync.RWMutex
|
||
|
|
||
|
func CompileToGetCodeSet(typeptr uintptr) (*opcodeSet, error) {
|
||
|
if typeptr > maxTypeAddr {
|
||
|
return compileToGetCodeSetSlowPath(typeptr)
|
||
|
}
|
||
|
index := typeptr - 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()
|
||
|
codeSet := &opcodeSet{
|
||
|
Code: code,
|
||
|
CodeLength: codeLength,
|
||
|
}
|
||
|
setsMu.Lock()
|
||
|
cachedOpcodeSets[index] = codeSet
|
||
|
setsMu.Unlock()
|
||
|
return codeSet, nil
|
||
|
}
|