package encoder
import (
"encoding/json"
stderrors "errors"
"reflect"
"sync"
"unsafe"
"github.com/goccy/go-json/internal/errors"
"github.com/goccy/go-json/internal/runtime"
)
var V2Hooks struct {
MarshalerToType reflect .Type
FormatRaw func (ctx *RuntimeContext , b, raw []byte ) ([]byte , error )
AppendRawMembers func (ctx *RuntimeContext , b, raw []byte , insertName func (name []byte ) bool ) ([]byte , error )
MarshalTo func (ctx *RuntimeContext , b []byte , typ reflect .Type , recv any ) ([]byte , error )
MarshalToOf func (typ reflect .Type , appendDefault AppendFunc ) AppendFunc
}
var ErrUseDefault = stderrors .New ("use the default representation" )
func implementsAddr(t , iface reflect .Type ) bool {
return t .Implements (iface ) || reflect .PointerTo (t ).Implements (iface )
}
const allMethods = -1
const (
noMethod = iota
methodMarshalJSONTo
methodMarshalJSON
methodAppendText
methodMarshalText
)
func v2MethodOf(typ reflect .Type , after int ) int {
if typ .Kind () == reflect .Pointer || typ .Kind () == reflect .Interface {
return noMethod
}
switch {
case after < methodMarshalJSONTo && V2Hooks .MarshalerToType != nil && implementsAddr (typ , V2Hooks .MarshalerToType ):
return methodMarshalJSONTo
case after < methodMarshalJSON && implementsAddr (typ , marshalJSONType ):
return methodMarshalJSON
case after < methodAppendText && implementsAddr (typ , appendTextType ):
return methodAppendText
case after < methodMarshalText && implementsAddr (typ , marshalTextType ):
return methodMarshalText
}
return noMethod
}
func (c *Compiler ) v2MethodOfAt (typ reflect .Type , after int , addressable bool ) int {
return methodOfAt (typ , after , addressable || c .v1Options &modeCallMethodsWithLegacySemantics == 0 )
}
func methodOfAt(typ reflect .Type , after int , addressable bool ) int {
m := v2MethodOf (typ , after )
for !addressable && m != noMethod && !typ .Implements (marshalerTypeOf (m )) {
m = v2MethodOf (typ , m )
}
return m
}
func marshalerTypeOf(m int ) reflect .Type {
switch m {
case methodMarshalJSONTo :
return V2Hooks .MarshalerToType
case methodMarshalJSON :
return marshalJSONType
case methodAppendText :
return appendTextType
}
return marshalTextType
}
func v2MethodOfInterface(typ reflect .Type ) int {
for m := methodMarshalJSONTo ; m <= methodMarshalText ; m ++ {
if iface := marshalerTypeOf (m ); iface != nil && typ .Implements (iface ) {
return m
}
}
return noMethod
}
func appendV1Interface(typ reflect .Type , m int ) AppendFunc {
return func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
v := reflect .NewAt (typ , p ).Elem ()
if v .IsNil () {
return append (b , "null" ...), nil
}
held := v .Elem ()
if held .Kind () != reflect .Pointer || !held .IsNil () || held .Type ().Elem ().Implements (marshalerTypeOf (m )) {
value := held .Interface ()
return appendValueOf (ctx , b , emptyInterfaceType , unsafe .Pointer (&value ))
}
recv := v .Interface ()
switch m {
case methodMarshalJSONTo :
return V2Hooks .MarshalTo (ctx , b , held .Type (), recv )
case methodMarshalJSON :
raw , err := recv .(json .Marshaler ).MarshalJSON ()
return appendV2Raw (ctx , held .Type (), b , raw , err )
}
return appendTextOf (ctx , b , held .Type (), m , recv )
}
}
func (c *Compiler ) v2HasMethod (typ reflect .Type ) bool {
return c .v2HasMethodAt (typ , true )
}
func (c *Compiler ) v2HasMethodAt (typ reflect .Type , addressable bool ) bool {
if typ == c .v2DefaultType {
return c .v2MethodOfAt (typ , c .v2DefaultAfter , addressable ) != noMethod
}
return len (c .funcs .funcsOf (typ )) > 0 || c .v2MethodOfAt (typ , noMethod , addressable ) != noMethod
}
func (c *Compiler ) v2MethodCode (typ reflect .Type , after int , addressable bool ) (Code , bool ) {
switch c .v2MethodOfAt (typ , after , addressable ) {
case methodMarshalJSONTo :
return c .appendFuncCode (typ , V2Hooks .MarshalToOf (typ , func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
return appendDefault (ctx , b , typ , p , methodMarshalJSONTo , addressable )
})), true
case methodMarshalJSON :
if typ == rawMessageType {
return c .appendFuncCode (typ , func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
raw := *(*[]byte )(p )
if raw == nil {
raw = nullJSON
}
out , err := AppendRaw (ctx , b , raw )
if err != nil {
return b , &errors .MethodError {GoType : typ , Err : err , Kind : errors .MethodMarshalJSON }
}
return out , nil
}), true
}
appendOutput := addrJSONAppender (typ )
marshalJSON := addrMethod [func (unsafe .Pointer ) ([]byte , error )](typ , marshalJSONInterface )
code := c .appendFuncCode (typ , func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
if appendOutput != nil {
if out , ok := appendOutput (b , p ); ok {
return out , nil
}
}
raw , err := marshalJSON (p )
return appendV2Raw (ctx , typ , b , raw , err )
})
if m := newMarshalerCall (reflect .PointerTo (typ ), marshalJSONInterface ); m != nil {
m .nilIsNull , m .trusted , m .appendOutput , m .v2Raw , m .recv = false , false , appendOutput , true , typ
m .appendValue = code .appendValue
code .call = m
}
return code , true
case methodAppendText :
appendText := addrMethod [func (unsafe .Pointer , []byte ) ([]byte , error )](typ , appendTextInterface )
return c .appendFuncCode (typ , func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
return appendMethodText (ctx , b , typ , errors .MethodAppendText , p , appendText )
}), true
case methodMarshalText :
marshalText := addrMethod [func (unsafe .Pointer ) ([]byte , error )](typ , marshalTextInterface )
return c .appendFuncCode (typ , func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
return appendMethodText (ctx , b , typ , errors .MethodMarshalText , p , func (p unsafe .Pointer , dst []byte ) ([]byte , error ) {
text , err := marshalText (p )
return append (dst , text ...), err
})
}), true
}
return nil , false
}
var (
rawMessageType = reflect .TypeOf (json .RawMessage (nil ))
nullJSON = []byte ("null" )
)
func appendV2Raw(ctx *RuntimeContext , typ reflect .Type , b , raw []byte , err error ) ([]byte , error ) {
if err == nil && ctx .Option .Flag &(RawRewriteOption |NormalizeUTF8Option |HTMLEscapeOption ) == 0 && len (raw ) > 0 &&
!notPureRaw .Has (raw ) && walkRaw [plainStrings ](nil , raw , ctx .levelsOfRaw ()) {
return append (b , raw ...), nil
}
if err != nil {
return b , &errors .MethodError {GoType : typ , Err : unsupportedError (err , errors .MethodMarshalJSON ), Kind : errors .MethodMarshalJSON }
}
out , err := AppendRaw (ctx , b , raw )
if err != nil {
return b , &errors .MethodError {GoType : typ , Err : err , Kind : errors .MethodMarshalJSON }
}
return out , nil
}
func AppendRaw (ctx *RuntimeContext , b , raw []byte ) ([]byte , error ) {
if ctx .Option .Flag &RawRewriteOption == 0 {
if out , ok := AppendFormattedRaw (ctx , b , raw ); ok {
return out , nil
}
}
return V2Hooks .FormatRaw (ctx , b , raw )
}
func addrMethod[F any ](typ reflect .Type , iface *marshalerInterface ) F {
fn , _ := methodCode (reflect .PointerTo (typ ), iface )
code := &fn
return *(*F )(unsafe .Pointer (&code ))
}
func addrJSONAppender(typ reflect .Type ) func ([]byte , unsafe .Pointer ) ([]byte , bool ) {
if runtime .IsStdMarshalerType (typ ) {
return stdJSONAppender (typ )
}
if origin , offset , inline , ok := runtime .PromotedStdMethod (typ , runtime .MarshalJSONMethod ); ok && inline {
return embeddedAppender (stdJSONAppender (origin ), offset )
}
return nil
}
var RunHook func (ctx *RuntimeContext , b []byte , codeSet *OpcodeSet ) ([]byte , error )
type defaultKey struct {
typ reflect .Type
mode compileMode
addressable bool
after int
}
var defaultCodeSets sync .Map
func appendDefault(ctx *RuntimeContext , b []byte , typ reflect .Type , p unsafe .Pointer , after int , addressable bool ) ([]byte , error ) {
mode := ctx .compileMode ()
key := defaultKey {typ : typ , mode : mode , after : after , addressable : addressable && mode &modeCallMethodsWithLegacySemantics != 0 }
var funcs *MarshalFuncs
cache := &defaultCodeSets
if ctx .Option .Flag &MarshalFuncsOption != 0 {
funcs = ctx .Option .Funcs
cache = &funcs .defaults
}
v , ok := cache .Load (key )
if !ok {
c := newCompiler (key .mode )
c .funcs = funcs
if after != allMethods {
c .v2DefaultType , c .v2DefaultAfter = typ , after
}
valueCode := c .valueCode
if key .addressable {
valueCode = c .pointeeCode
}
code , err := valueCode (typ )
if err != nil {
return b , err
}
codeSet , err := c .codeToOpcodeSet (typ , code )
if err != nil {
return b , err
}
v , _ = cache .LoadOrStore (key , codeSet )
}
codeSet := v .(*OpcodeSet )
return runInner (ctx , b , codeSet , p )
}
func appendAddressable(typ reflect .Type ) AppendFunc {
return func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
return appendDefault (ctx , b , typ , p , allMethods , true )
}
}
func runInner(ctx *RuntimeContext , b []byte , codeSet *OpcodeSet , p unsafe .Pointer ) ([]byte , error ) {
if ctx .ValueDepth +codeSet .Levels > MaxDepth {
return b , &errors .OutputError {Out : b , Err : ErrMaxDepth (ctx )}
}
inner := TakeRuntimeContext ()
*inner .Option = *ctx .Option
SetFlags (inner , ctx .Option .Flag )
inner .Option .EscaperFlags = noEscaperFlags
inner .Init (p , codeSet .CodeLength )
inner .BaseIndent = ctx .ValueDepth
inner .Prefix , inner .IndentStr = ctx .Prefix , ctx .IndentStr
inner .RescanNames = false
inner .RewriteFrom = ctx .RewriteFrom
out , err := b , EnterNested (inner , ctx , codeSet , p )
if err == nil {
out , err = RunHook (inner , b , codeSet )
}
if invalidOut , invalid := inner .InvalidUTF8Output (); invalid {
out , err = invalidOut , &errors .TextError {Err : errors .ErrInvalidUTF8 }
}
ctx .RescanNames = ctx .RescanNames || inner .RescanNames
ctx .RewriteFrom = inner .RewriteFrom
inner .Option .V2 , inner .Option .Funcs = nil , nil
ReleaseRuntimeContext (inner )
if err != nil {
if _ , ok := err .(*errors .OutputError ); !ok {
err = &errors .OutputError {Out : out , Err : err }
}
return b , err
}
end := len (out ) - 1
if ctx .Option .Flag &IndentOption != 0 {
end --
}
ctx .Rewrote (end )
return out [:end ], nil
}
func appendMethodText(ctx *RuntimeContext , b []byte , typ reflect .Type , kind errors .MethodKind , p unsafe .Pointer , appendText func (unsafe .Pointer , []byte ) ([]byte , error )) ([]byte , error ) {
start := len (b )
text , err := appendText (p , ctx .MarshalBuf [:0 ])
if err != nil {
return b , &errors .MethodError {GoType : typ , Err : unsupportedError (err , kind ), Kind : kind }
}
ctx .MarshalBuf = text [:0 ]
out , err := appendName (ctx , b , *(*string )(unsafe .Pointer (&text )))
if err != nil {
return b [:start ], &errors .MethodError {GoType : typ , Err : err , Kind : kind }
}
return out , nil
}
func unsupportedError(err error , kind errors .MethodKind ) error {
if stderrors .Is (err , stderrors .ErrUnsupported ) {
return stderrors .New (kind .String () + " method may not return errors.ErrUnsupported" )
}
return err
}
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 .