package encoder
import (
"errors"
"fmt"
"reflect"
"slices"
"sync"
"time"
"unsafe"
ierrors "github.com/goccy/go-json/internal/errors"
"github.com/goccy/go-json/internal/jsonfields"
"github.com/goccy/go-json/internal/jsonstring"
"github.com/goccy/go-json/internal/runtime"
)
var (
timeDurationType = reflect .TypeFor [time .Duration ]()
timeTimeType = reflect .TypeFor [time .Time ]()
)
var (
errYearRange = errors .New ("year outside of range [0,9999]" )
errTimezoneRange = errors .New ("timezone hour outside of range [0,23]" )
errNoDuration = errors .New ("no default representation" )
)
func appendTime(_ *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
t := (*time .Time )(p )
if year := t .Year (); year < 0 || year > 9999 {
return b , &ierrors .MethodError {GoType : timeTimeType , Err : errYearRange , Kind : ierrors .MethodMarshalJSON }
}
if _ , offset := t .Zone (); offset <= -24 *60 *60 || offset >= 24 *60 *60 {
return b , &ierrors .MethodError {GoType : timeTimeType , Err : errTimezoneRange , Kind : ierrors .MethodMarshalJSON }
}
b = append (b , '"' )
b = t .AppendFormat (b , time .RFC3339Nano )
return append (b , '"' ), nil
}
func (c *Compiler ) v2Code (typ reflect .Type , addressable bool ) (Code , bool ) {
after , isDefault := noMethod , typ == c .v2DefaultType
switch {
case c .nextIsEmbedded :
return nil , false
case c .stringTag :
code , applies := c .stringTagCode (typ , addressable )
switch {
case code != nil :
return code , true
case !applies :
after := allMethods
if isDefault {
after = c .v2DefaultAfter
}
return c .appendFuncCode (typ , appendWithoutStringTag (typ , after , addressable )), true
}
}
switch {
case isDefault :
after = c .v2DefaultAfter
c .v2DefaultType = nil
default :
if code , ok := c .v2FuncsCode (typ , addressable ); ok {
return code , true
}
}
switch {
case typ == timeDurationType && c .v1Options &modeFormatDurationAsNano == 0 :
return c .appendFuncCode (typ , appendError (typ , errNoDuration )), true
case typ == timeTimeType :
return c .appendFuncCode (typ , appendTime ), true
}
if code , ok := c .v2MethodCode (typ , after , addressable ); ok {
return code , true
}
switch typ .Kind () {
case reflect .Interface :
if c .v1Options &modeCallMethodsWithLegacySemantics == 0 {
break
}
if m := v2MethodOfInterface (typ ); m != noMethod {
return c .appendFuncCode (typ , appendV1Interface (typ , m )), true
}
case reflect .Struct :
if fields := v2FieldsOf (typ ); fields .Err != nil && c .v1Options &modeReportErrorsWithLegacySemantics == 0 {
return c .appendFuncCode (typ , appendError (fields .Err .GoType , fields .Err .Err )), true
} else if fields .FormatErr != nil {
return c .appendFuncCode (typ , appendError (fields .FormatErr .GoType , fields .FormatErr .Err )), true
}
case reflect .Complex64 , reflect .Complex128 , reflect .Chan , reflect .Func , reflect .UnsafePointer :
return c .appendFuncCode (typ , appendError (typ , nil )), true
case reflect .Slice :
if elem := typ .Elem (); elem .Kind () == reflect .Uint8 && elem .PkgPath () != "" {
if !v2BytesAsArray (typ , c .v1Options &modeFormatByteArrayAsArray != 0 ,
c .v1Options &modeFormatBytesWithLegacySemantics != 0 ) {
code , _ := c .bytesCode (typ , false )
return code , true
}
code , err := c .sliceCode (typ )
if err != nil {
return nil , false
}
return code , true
}
case reflect .Array :
if typ .Elem ().Kind () == reflect .Uint8 && !v2BytesAsArray (typ , c .v1Options &modeFormatByteArrayAsArray != 0 ,
c .v1Options &modeFormatBytesWithLegacySemantics != 0 ) {
n := typ .Len ()
return c .appendFuncCode (typ , func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
return AppendByteSlice (ctx , b , unsafe .Slice ((*byte )(p ), n )), nil
}), true
}
case reflect .Ptr :
if kind := typ .Elem ().Kind (); (kind == reflect .Map || kind == reflect .Slice ) &&
(c .v1Options &modeCallMethodsWithLegacySemantics == 0 || !c .v2HasMethod (typ .Elem ())) {
return &PtrCode {typ : typ , value : &InterfaceCode {typ : typ .Elem (), static : true }, ptrNum : 1 }, true
}
}
return nil , false
}
func v2BytesAsArray(typ reflect .Type , byteArrayAsArray , formatBytesWithLegacySemantics bool ) bool {
elem := typ .Elem ()
switch {
case typ .Kind () == reflect .Array && byteArrayAsArray :
return true
case elem .PkgPath () == "" :
return false
}
return !formatBytesWithLegacySemantics || v2MethodOf (elem , noMethod ) != noMethod
}
func (c *Compiler ) appendFuncCode (typ reflect .Type , fn AppendFunc ) *MarshalJSONCode {
return &MarshalJSONCode {typ : typ , appendValue : fn , isAddrForMarshaler : true }
}
func hasNoRepresentation(kind reflect .Kind ) bool {
switch kind {
case reflect .Complex64 , reflect .Complex128 , reflect .Chan , reflect .Func , reflect .UnsafePointer :
return true
}
return false
}
func appendError(typ reflect .Type , err error ) AppendFunc {
return func (_ *RuntimeContext , b []byte , _ unsafe .Pointer ) ([]byte , error ) {
return b , &ierrors .SemanticError {GoType : typ , Err : err }
}
}
var v2Fields sync .Map
func v2FieldsOf(t reflect .Type ) *jsonfields .Fields {
if fields , ok := v2Fields .Load (t ); ok {
return fields .(*jsonfields .Fields )
}
fields , _ := v2Fields .LoadOrStore (t , jsonfields .Of (t ))
return fields .(*jsonfields .Fields )
}
type v2Object struct {
members map [string ]*jsonfields .Field
embeds map [string ]bool
path []int
}
func indexKey(index []int ) string {
return fmt .Sprint (index )
}
func newV2Object(fields *jsonfields .Fields ) *v2Object {
obj := &v2Object {members : map [string ]*jsonfields .Field {}, embeds : map [string ]bool {}}
for i := range fields .List {
f := &fields .List [i ]
obj .members [indexKey (f .Index )] = f
for n := 1 ; n < len (f .Index ); n ++ {
obj .embeds [indexKey (f .Index [:n ])] = true
}
}
return obj
}
func (c *Compiler ) v2StructTags (typ reflect .Type , embedded bool ) (runtime .StructTags , map [*runtime .StructTag ][]int , func ()) {
saved := c .v2Object
var obj *v2Object
if embedded && saved != nil {
obj = &v2Object {members : saved .members , embeds : saved .embeds , path : c .v2EmbedPath }
} else {
obj = newV2Object (v2FieldsOf (typ ))
}
c .v2Object = obj
var tags runtime .StructTags
embeds := map [*runtime .StructTag ][]int {}
for i := range typ .NumField () {
path := append (slices .Clip (obj .path ), i )
key := indexKey (path )
sf := typ .Field (i )
if m , ok := obj .members [key ]; ok {
tags = append (tags , &runtime .StructTag {
Key : m .Name ,
QuotedKey : m .QuotedName ,
IsTaggedKey : m .HasName ,
IsOmitEmpty : m .OmitEmpty ,
IsOmitZero : m .OmitZero || c .omitZeroStructFields ,
IsString : m .String ,
Field : sf ,
})
} else if obj .embeds [key ] {
tag := &runtime .StructTag {Key : sf .Name , Field : sf }
tags = append (tags , tag )
embeds [tag ] = path
}
}
return tags , embeds , func () { c .v2Object = saved }
}
func (c *Compiler ) v2HiddenNames (typ reflect .Type , path []int ) []string {
written := map [string ]bool {}
for _ , m := range c .v2Object .members {
if len (m .Index ) > len (path ) && slices .Equal (m .Index [:len (path )], path ) {
written [m .Name ] = true
}
}
var hidden []string
for _ , m := range v2FieldsOf (typ ).List {
if !written [m .Name ] {
hidden = append (hidden , m .Name )
}
}
return hidden
}
var errInvalidStringTag = errors .New ("invalid use of `string` tag option" )
func (c *Compiler ) v2FieldValueCode (field *StructFieldCode , addressable bool ) (Code , bool ) {
tag := *field .tag
field .tag = &tag
if tag .IsOmitEmpty && c .v1Options &modeOmitEmptyWithLegacySemantics == 0 {
switch kind := field .typ .Kind (); {
case kind == reflect .Ptr && !c .v2HasMethod (field .typ ) && c .v2NeverEmpty (field .typ .Elem ()):
case kind == reflect .Ptr && !c .v2HasMethod (field .typ ) && !c .v2HasMethod (field .typ .Elem ()) &&
field .typ .Elem ().Kind () == reflect .String && !tag .IsString :
field .omitEmptyString = true
case (kind == reflect .Ptr || kind == reflect .Interface ) && len (c .funcs .funcsOf (field .typ )) == 0 :
field .unwriteEmpty = true
case field .typ == rawMessageType && v2MethodOf (field .typ , noMethod ) == methodMarshalJSON &&
len (c .funcs .funcsOf (field .typ )) == 0 :
field .emptyNil = true
field .unwriteEmpty = true
case c .v2HasMethod (field .typ ):
tag .IsOmitEmpty = false
field .unwriteEmpty = true
case c .v2NeverEmpty (field .typ ):
tag .IsOmitEmpty = false
case kind == reflect .String || kind == reflect .Map || kind == reflect .Slice || kind == reflect .Array :
default :
tag .IsOmitEmpty = false
field .unwriteEmpty = true
}
}
field .isNilCheck = tag .IsOmitEmpty || field .typ .Kind () == reflect .Ptr
if !tag .IsString {
return nil , false
}
code , applies := c .stringTagCode (field .typ , addressable )
if applies && code == nil {
return nil , false
}
tag .IsString = false
return code , code != nil
}
func (c *Compiler ) stringTagCode (typ reflect .Type , addressable bool ) (Code , bool ) {
elem := typ
ptrNum := 0
var passed []reflect .Type
for elem .Kind () == reflect .Ptr && !c .v2HasMethod (elem ) && !slices .Contains (passed , elem ) {
passed = append (passed , elem )
elem = elem .Elem ()
ptrNum ++
}
stringify := c .v1Options &modeStringifyWithLegacySemantics != 0
reportErrors := c .v1Options &modeReportErrorsWithLegacySemantics != 0
addressable = addressable || ptrNum > 0
ptrToPtr := typ .Kind () == reflect .Ptr && typ .Elem ().Kind () == reflect .Ptr && !c .v2HasMethod (typ )
var code Code
switch {
case stringify && ptrToPtr && reportErrors :
return nil , false
case stringify && ptrToPtr :
return c .appendFuncCode (typ , appendError (typ , errInvalidStringTag )), true
case c .v2HasMethodAt (elem , addressable ) && elem != timeTimeType ,
reportErrors && !stringify && elem .Kind () == reflect .Interface :
if c .stringTag {
return nil , true
}
code = c .appendFuncCode (elem , appendStringTag (elem , addressable ))
case elem .Kind () == reflect .Ptr :
return nil , false
case elem == timeDurationType && c .v1Options &modeFormatDurationAsNano == 0 :
code = c .appendFuncCode (elem , appendError (elem , errNoDuration ))
case isNumberKind (elem .Kind ()) || elem == jsonNumberType :
return nil , true
case stringify && elem .Kind () == reflect .Bool :
code = c .appendFuncCode (elem , appendStringifiedBool )
case stringify && elem .Kind () == reflect .String :
code = c .appendFuncCode (elem , appendStringifiedString (elem ))
case hasNoRepresentation (elem .Kind ()):
code = c .appendFuncCode (elem , appendError (elem , nil ))
case reportErrors :
return nil , false
default :
code = c .appendFuncCode (elem , appendError (elem , errInvalidStringTag ))
}
if ptrNum > 0 {
code = &PtrCode {typ : typ , value : code , ptrNum : uint8 (ptrNum )}
}
return code , true
}
func appendStringifiedBool(_ *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
if *(*bool )(p ) {
return append (b , `"true"` ...), nil
}
return append (b , `"false"` ...), nil
}
func appendStringifiedString(typ reflect .Type ) AppendFunc {
return func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
quoted , ok := jsonstring .AppendQuoted (textEscaper (ctx ), ctx .MarshalBuf [:0 ], *(*string )(p ))
if !ok {
var err error
if quoted , err = InvalidUTF8 (ctx , nil , quoted ); err != nil {
return b , &ierrors .SemanticError {GoType : typ , Err : err }
}
}
ctx .MarshalBuf = quoted [:0 ]
out , _ := jsonstring .AppendQuoted (jsonstring .EscaperOf (uint (TextEscapeOption )), b , *(*string )(unsafe .Pointer ("ed )))
return out , nil
}
}
func appendStringTag(typ reflect .Type , addressable bool ) AppendFunc {
return func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
flags := ctx .Option .Flag
ctx .Option .Flag |= StringTagOption
out , err := appendDefault (ctx , b , typ , p , allMethods , addressable )
ctx .Option .Flag = flags
return out , err
}
}
func appendWithoutStringTag(typ reflect .Type , after int , addressable bool ) AppendFunc {
return func (ctx *RuntimeContext , b []byte , p unsafe .Pointer ) ([]byte , error ) {
flags := ctx .Option .Flag
ctx .Option .Flag &^= StringTagOption
out , err := appendDefault (ctx , b , typ , p , after , addressable )
ctx .Option .Flag = flags
return out , err
}
}
func (c *Compiler ) v2NeverEmpty (typ reflect .Type ) bool {
if c .v2HasMethod (typ ) {
return typ != c .v2DefaultType && len (c .funcs .funcsOf (typ )) == 0 &&
v2MethodOf (typ , noMethod ) == methodMarshalJSON && addrJSONAppender (typ ) != nil
}
switch kind := typ .Kind (); {
case kind == reflect .Bool || isNumberKind (kind ), typ == jsonNumberType :
return true
case kind == reflect .Struct && !c .omitZeroStructFields :
fields := v2FieldsOf (typ )
if fields .Err != nil {
return false
}
for _ , f := range fields .List {
if !f .OmitEmpty && !f .OmitZero && len (f .Index ) == 1 {
return true
}
}
}
return false
}
func isNumberKind(kind reflect .Kind ) bool {
switch kind {
case reflect .Int , reflect .Int8 , reflect .Int16 , reflect .Int32 , reflect .Int64 ,
reflect .Uint , reflect .Uint8 , reflect .Uint16 , reflect .Uint32 , reflect .Uint64 , reflect .Uintptr ,
reflect .Float32 , reflect .Float64 :
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 .