package decoder
import (
"bytes"
"encoding/base64"
"encoding/binary"
stderrors "errors"
"fmt"
"math/bits"
"reflect"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"unsafe"
"github.com/goccy/go-json/internal/errors"
"github.com/goccy/go-json/internal/jsonnum"
"github.com/goccy/go-json/internal/runtime"
)
var (
errV2Text = stderrors .New ("json: invalid text of encoding/json/v2" )
errNilInterface = stderrors .New ("cannot derive concrete type for nil interface with finite type set" )
errV2DuplicateName = stderrors .New ("json: duplicate name of encoding/json/v2" )
errNoDefaultRepresentation = stderrors .New ("no default representation" )
errArrayUnderflow = stderrors .New ("too few array elements" )
errArrayOverflow = stderrors .New ("too many array elements" )
)
var timeDurationType = reflect .TypeOf (time .Duration (0 ))
func IsArrayLengthError (err error ) bool {
return err == errArrayOverflow || err == errArrayUnderflow
}
var cachedV2Decoders [2 ]runtime .TypeCache [Decoder ]
const v1DecoderOptions = V2CallMethodsWithLegacySemantics | V2FormatByteArrayAsArray |
V2FormatBytesWithLegacySemantics | V2FormatDurationAsNano | V2ReportErrorsWithLegacySemantics |
V2StringifyWithLegacySemantics
type flagsKey struct {
typeptr uintptr
flags V2Flags
}
var v1OptionDecoders sync .Map
func decoderIn(m *sync .Map , typ unsafe .Pointer , flags V2Flags , funcs *UnmarshalFuncs ) (Decoder , error ) {
key := flagsKey {typeptr : uintptr (typ ), flags : flags & (v1DecoderOptions | V2StringifyNumbers )}
if v , ok := m .Load (key ); ok {
return v .(Decoder ), nil
}
c := newCompiler (true )
c .stringifyNumbers , c .v1Options , c .funcs = flags &V2StringifyNumbers != 0 , flags &v1DecoderOptions , funcs
dec , err := compileHead (runtime .TypeOfPtr (typ ), c )
if err != nil {
return nil , err
}
v , _ := m .LoadOrStore (key , dec )
return v .(Decoder ), nil
}
func CompileToGetDecoderV2 (typ unsafe .Pointer , flags V2Flags ) (Decoder , error ) {
if flags &v1DecoderOptions != 0 {
return decoderIn (&v1OptionDecoders , typ , flags , nil )
}
stringifyNumbers := flags &V2StringifyNumbers != 0
cache := &cachedV2Decoders [0 ]
if stringifyNumbers {
cache = &cachedV2Decoders [1 ]
}
typeptr := uintptr (typ )
if dec := cache .Load (typeptr ); dec != nil {
return *dec , nil
}
c := newCompiler (true )
c .stringifyNumbers = stringifyNumbers
dec , err := compileHead (runtime .TypeOfPtr (typ ), c )
if err != nil {
return nil , err
}
return *cache .Store (typeptr , &dec ), nil
}
const (
v2DecoderMark = 1
stringifyDecoderMark = 2
)
func (ctx *RuntimeContext ) DecoderOfV2 (typ unsafe .Pointer ) (Decoder , error ) {
if funcs := ctx .v2Funcs (); funcs != nil {
return funcs .decoderOf (typ , ctx .Option .V2 )
}
flags := ctx .Option .V2
if ctx .recentDecoders == nil {
return CompileToGetDecoderV2 (typ , flags )
}
key := uintptr (typ ) | v2DecoderMark
if flags &V2StringifyNumbers != 0 {
key |= stringifyDecoderMark
}
set := &ctx .recentDecoders [(uint64 (key )*runtime .TypeHashMultiplier )>>recentDecoderHashShift ]
if set [0 ].typeptr == key {
return set [0 ].dec , nil
}
if set [1 ].typeptr == key {
return set [1 ].dec , nil
}
dec , err := CompileToGetDecoderV2 (typ , flags )
if err != nil {
return nil , err
}
set .keep (key , dec )
return dec , nil
}
func SetV2Flags (ctx *RuntimeContext , flags V2Flags ) {
ctx .Option .V2 = flags
if v1Options := flags & v1DecoderOptions ; v1Options != ctx .recentV1Options {
emptyRecentDecoders (ctx , v1Options )
}
}
func emptyRecentDecoders(ctx *RuntimeContext , v1Options V2Flags ) {
if ctx .recentDecoders != nil {
*ctx .recentDecoders = [recentDecoderSets ]recentDecoderSet {}
}
ctx .recentV1Options = v1Options
}
func (c *compiler ) compileV2 (typ reflect .Type , structName , fieldName string ) (Decoder , error ) {
if dec , exists := c .decoders [uintptr (runtime .TypePtr (typ ))]; exists {
return dec , nil
}
first := methodUnmarshalJSONFrom
if c .mapKeys && c .v1Options &V2CallMethodsWithLegacySemantics != 0 {
first = methodUnmarshalText
}
if funcs := c .funcs .funcsOf (typ ); len (funcs ) > 0 {
d := &v2FuncDecoder {typ : typ , funcs : funcs }
return d , c .compileNextV2 (d , &d .next , typ , first , structName , fieldName )
}
return c .compileDefaultV2 (typ , first , structName , fieldName )
}
func (c *compiler ) compileNextV2 (dec Decoder , next *Decoder , typ reflect .Type , first int , structName , fieldName string ) error {
key := uintptr (runtime .TypePtr (typ ))
switch typ .Kind () {
case reflect .Struct , reflect .Map , reflect .Slice , reflect .Array , reflect .Pointer :
if _ , exists := c .decoders [key ]; !exists {
c .decoders [key ] = dec
}
}
d , err := c .compileDefaultV2 (typ , first , structName , fieldName )
*next = d
return err
}
func (c *compiler ) compileDefaultV2 (typ reflect .Type , first int , structName , fieldName string ) (Decoder , error ) {
switch {
case typ == timeDurationType && c .v1Options &V2FormatDurationAsNano == 0 :
return &v2InvalidDecoder {typ : typ , err : errNoDefaultRepresentation }, nil
case typ == timeType :
if c .stringTag {
return &v2InvalidDecoder {typ : typ , err : errInvalidStringTag }, nil
}
return v2TimeDecoder {}, nil
}
switch v2MethodOf (typ , first ) {
case methodUnmarshalJSONFrom :
d := &v2UnmarshalFromDecoder {typ : typ }
return d , c .compileNextV2 (d , &d .next , typ , methodUnmarshalJSON , structName , fieldName )
case methodUnmarshalJSON :
return &v2UnmarshalJSONDecoder {typ : typ , ptrType : runtime .TypePtr (reflect .PointerTo (typ ))}, nil
case methodUnmarshalText :
return &v2UnmarshalTextDecoder {typ : typ , ptrType : runtime .TypePtr (reflect .PointerTo (typ )), zero : newZeroer (typ )}, nil
}
stringify := c .stringTag && c .v1Options &V2StringifyWithLegacySemantics != 0
if c .stringTag && typ .Kind () != reflect .Ptr && !isNumberKind (typ .Kind ()) && !hasNoRepresentation (typ .Kind ()) {
if stringify && typ != jsonNumberType && (typ .Kind () == reflect .Bool || typ .Kind () == reflect .String ) {
return &v2StringifiedDecoder {typ : typ }, nil
}
return &v2InvalidDecoder {typ : typ , err : errInvalidStringTag }, nil
}
switch kind := typ .Kind (); kind {
case reflect .Ptr :
if stringify {
return c .compileStringifiedPtrV2 (typ , structName , fieldName )
}
return compilePtr (typ , structName , fieldName , c )
case reflect .Slice :
if IsV2Bytes (typ , c .v1Options ) {
return c .compileBytesV2 (typ , structName , fieldName )
}
return compileSlice (typ , structName , fieldName , c )
case reflect .Array :
if IsV2Bytes (typ , c .v1Options ) {
return c .compileBytesV2 (typ , structName , fieldName )
}
return c .compileArrayV2 (typ , structName , fieldName )
case reflect .Interface :
return c .newV2InterfaceDecoder (typ ), nil
case reflect .String :
d := newStringDecoder (structName , fieldName )
d .typ = typ
return v2StringDecoder {d }, nil
case reflect .Bool ,
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 :
if c .stringifyNumbers && kind != reflect .Bool {
return newV2StringNumberDecoder (typ ), nil
}
return compileKind (typ , structName , fieldName , c )
case reflect .Struct :
return c .compileStructV2 (typ )
case reflect .Map :
return c .compileMapV2 (typ , structName , fieldName )
}
return &v2InvalidDecoder {typ : typ }, nil
}
func hasNoRepresentation(kind reflect .Kind ) bool {
switch kind {
case reflect .Complex64 , reflect .Complex128 , reflect .Chan , reflect .Func , reflect .UnsafePointer :
return true
}
return false
}
func IsV2Bytes (typ reflect .Type , flags V2Flags ) bool {
elem := typ .Elem ()
if elem .Kind () != reflect .Uint8 || typ .Kind () == reflect .Array && flags &V2FormatByteArrayAsArray != 0 {
return false
}
return elem .PkgPath () == "" || flags &V2FormatBytesWithLegacySemantics != 0
}
func (c *compiler ) compileBytesV2 (typ reflect .Type , structName , fieldName string ) (Decoder , error ) {
d := newV2BytesDecoder (typ )
if c .v1Options &V2FormatBytesWithLegacySemantics == 0 {
return d , nil
}
var elements Decoder
var err error
if typ .Kind () == reflect .Slice {
elements , err = compileSlice (typ , structName , fieldName , c )
} else {
elements , err = c .compileArrayV2 (typ , structName , fieldName )
}
if err != nil {
return nil , err
}
return &v2FormatBytesWithLegacySemanticsDecoder {bytes : d , elements : elements }, nil
}
func (ctx *RuntimeContext ) V2TypeError () error {
if ctx .typeError == nil {
return nil
}
return ctx .v2Error ()
}
func (ctx *RuntimeContext ) v2Error () error {
p := ctx .typeError
ctx .typeError = nil
if p .plain != nil {
return p .plain
}
e := &errors .UnmarshalError {GoType : p .typ , Start : p .start , End : p .end , Err : p .err }
if p .literal {
e .HasValue = true
e .Err = numberCause (ctx .Buf [p .start :p .end ], p .typ )
}
return e
}
func numberCause(num []byte , typ reflect .Type ) error {
switch typ .Kind () {
case reflect .Float32 , reflect .Float64 :
return strconv .ErrRange
case reflect .Uint , reflect .Uint8 , reflect .Uint16 , reflect .Uint32 , reflect .Uint64 , reflect .Uintptr :
if num [0 ] == '-' {
return strconv .ErrSyntax
}
}
if bytes .ContainsAny (num , ".eE" ) {
return strconv .ErrSyntax
}
return strconv .ErrRange
}
func validV2Text(text []byte ) bool {
return utf8 .Valid (text ) && !hasLoneSurrogate (text )
}
func hasLoneSurrogate(b []byte ) bool {
for {
i := bytes .IndexByte (b , '\\' )
if i < 0 {
return false
}
if b [i +1 ] != 'u' {
b = b [i +2 :]
continue
}
code := hexValue (b [i +2 : i +6 ])
b = b [i +6 :]
switch {
case code >= 0xdc00 && code < 0xe000 :
return true
case code >= 0xd800 && code < 0xdc00 :
if len (b ) < 6 || b [0 ] != '\\' || b [1 ] != 'u' {
return true
}
if low := hexValue (b [2 :6 ]); low < 0xdc00 || low >= 0xe000 {
return true
}
b = b [6 :]
}
}
}
func hexValue(b []byte ) rune {
var r rune
for _ , c := range b {
switch {
case c <= '9' :
c -= '0'
case c <= 'F' :
c -= 'A' - 10
default :
c -= 'a' - 10
}
r = r <<4 | rune (c )
}
return r
}
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
}
type v2StringDecoder struct { *stringDecoder }
func (d v2StringDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
var (
s string
next int64
err error
)
buf := ctx .Buf
start := skipWhiteSpace (buf , cursor )
if buf [start ] == '"' {
s , next , err = decodeStringV2 (d .stringDecoder , ctx , start +1 )
} else {
var ok bool
if s , next , ok , err = d .decodeStringValue (ctx , start ); err == nil && ok {
err = replacedRuneError (ctx , s , start , next )
} else if err == nil && buf [start ] == 'n' && ctx .Option .V2 &V2MergeWithLegacySemantics != 0 {
return next , nil
}
}
if err != nil {
return 0 , err
}
**(**string )(unsafe .Pointer (&p )) = s
return next , nil
}
func decodeStringV2(d *stringDecoder , ctx *RuntimeContext , start int64 ) (string , int64 , error ) {
buf := ctx .Buf
b := (*sliceHeader )(unsafe .Pointer (&buf )).data
buflen := int64 (len (buf ))
cursor := start
wordsEnd := buflen
if hasStringSIMD {
wordsEnd = min (buflen , start +64 )
}
for cursor +8 <= wordsEnd {
w := load64 (buf , cursor )
if stop := keyEndBytes (w ) | w &msb ; stop != 0 {
cursor += int64 (bits .TrailingZeros64 (stop ) / 8 )
if char (b , cursor ) == '"' {
return ctx .makeString (buf [start :cursor ]), cursor + 1 , nil
}
break
}
cursor += 8
}
firstEscape := int64 (-1 )
nonASCII := false
ascii := uint64 (msb )
for {
c := char (b , cursor )
switch {
case c == '"' :
literal , next := buf [start :cursor ], cursor +1
if nonASCII && !utf8 .Valid (literal ) {
return decodeStringV1 (d , ctx , start )
}
if firstEscape < 0 {
return ctx .makeString (literal ), next , nil
}
return ctx .unescapeString (literal , stringInfo {firstEscape : int (firstEscape )}), next , nil
case c == '\\' :
switch char (b , cursor +1 ) {
case '"' , '\\' , '/' , 'b' , 'f' , 'n' , 'r' , 't' :
if firstEscape < 0 {
firstEscape = cursor - start
}
cursor += 2
default :
return decodeStringV1 (d , ctx , start )
}
case c >= 0x80 :
nonASCII , ascii = true , 0
cursor ++
case c >= 0x20 && wordsEnd == buflen :
cursor ++
default :
return decodeStringV1 (d , ctx , start )
}
for cursor +8 <= wordsEnd {
w := load64 (buf , cursor )
if stop := keyEndBytes (w ) | w &ascii ; stop != 0 {
cursor += int64 (bits .TrailingZeros64 (stop ) / 8 )
break
}
cursor += 8
}
}
}
func decodeStringV1(d *stringDecoder , ctx *RuntimeContext , start int64 ) (string , int64 , error ) {
s , next , _ , err := d .decodeStringField (ctx , start )
if err != nil {
return "" , 0 , err
}
if err := replacedRuneError (ctx , s , start -1 , next ); err != nil {
return "" , 0 , err
}
return s , next , nil
}
func replacedRuneError(ctx *RuntimeContext , s string , start , next int64 ) error {
if ctx .Option .V2 &V2AllowInvalidUTF8 == 0 && strings .IndexByte (s , 0xef ) >= 0 && !validV2Text (ctx .Buf [start :next ]) {
return errV2Text
}
return nil
}
type v2StringNumberDecoder struct {
typ reflect .Type
kind reflect .Kind
str *stringDecoder
}
func newV2StringNumberDecoder(typ reflect .Type ) *v2StringNumberDecoder {
return &v2StringNumberDecoder {typ : typ , kind : typ .Kind (), str : newStringDecoder ("" , "" )}
}
func (d *v2StringNumberDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
if ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
clear (unsafe .Slice ((*byte )(p ), d .typ .Size ()))
}
return cursor + 4 , nil
case '"' :
default :
return ctx .skipTypeError (cursor , depth , d .typ )
}
num , next , err := d .str .decodeByte (buf , cursor )
if err != nil {
return 0 , err
}
if !jsonnum .IsValid (num ) && ctx .Option .V2 &V2StringifyWithLegacySemantics == 0 {
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor , End : next , HasValue : true , Err : strconv .ErrSyntax }
}
if err := setNumber (p , d .kind , num ); err != nil {
if ctx .Option .V2 &V2StringifyWithLegacySemantics != 0 && string (num ) == "null" {
if ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
clear (unsafe .Slice ((*byte )(p ), d .typ .Size ()))
}
return next , nil
}
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor , End : next , HasValue : true , Err : err }
}
return next , nil
}
type v2StringifiedDecoder struct {
typ reflect .Type
}
func (d *v2StringifiedDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
d .zero (ctx , p )
return cursor + 4 , nil
case '"' :
default :
return ctx .skipTypeError (cursor , depth , d .typ )
}
var s string
end , err := v2StringDecoder {skipStringDecoder }.Decode (ctx , cursor , depth , unsafe .Pointer (&s ))
if err != nil {
return 0 , err
}
switch {
case s == "null" :
d .zero (ctx , p )
case d .typ .Kind () == reflect .Bool && (s == "true" || s == "false" ):
*(*bool )(p ) = s == "true"
case d .typ .Kind () == reflect .Bool :
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor , End : end , HasValue : true , Err : strconv .ErrSyntax }
default :
text , err := V2Hooks .AppendUnquote (nil , s )
if err != nil {
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor , Err : err }
}
*(*string )(p ) = string (text )
}
return end , nil
}
func (d *v2StringifiedDecoder ) zero (ctx *RuntimeContext , p unsafe .Pointer ) {
if ctx .Option .V2 &V2MergeWithLegacySemantics != 0 {
return
}
if d .typ .Kind () == reflect .Bool {
*(*bool )(p ) = false
} else {
*(*string )(p ) = ""
}
}
func (d *v2StringifiedDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
func (c *compiler ) compileStringifiedPtrV2 (typ reflect .Type , structName , fieldName string ) (Decoder , error ) {
d := &v2StringifiedPtrDecoder {}
if typ .Elem ().Kind () == reflect .Ptr {
d .ptr = &v2InvalidDecoder {typ : typ , err : errInvalidStringTag }
return d , nil
}
var err error
d .ptr , err = compilePtr (typ , structName , fieldName , c )
return d , err
}
type v2StringifiedPtrDecoder struct {
ptr Decoder
}
func (d *v2StringifiedPtrDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
if buf [cursor ] == 'n' {
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
*(*unsafe .Pointer )(p ) = nil
return cursor + 4 , nil
}
end , err := d .ptr .Decode (ctx , cursor , depth , p )
if err != nil {
return 0 , err
}
if raw := buf [cursor :end ]; string (raw ) == `"null"` || raw [0 ] == '"' && bytes .IndexByte (raw , '\\' ) >= 0 && d .isNull (ctx , cursor , depth ) {
*(*unsafe .Pointer )(p ) = nil
}
return end , nil
}
func (d *v2StringifiedPtrDecoder ) isNull (ctx *RuntimeContext , cursor , depth int64 ) bool {
var s string
_ , err := v2StringDecoder {skipStringDecoder }.Decode (ctx , cursor , depth , unsafe .Pointer (&s ))
return err == nil && s == "null"
}
func (d *v2StringifiedPtrDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
func (d *v2StringNumberDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
func setNumber(p unsafe .Pointer , kind reflect .Kind , num []byte ) error {
s := unsafe .String (unsafe .SliceData (num ), len (num ))
var err error
switch kind {
case reflect .Float32 , reflect .Float64 :
bits := 64
if kind == reflect .Float32 {
bits = 32
}
var f float64
if f , err = strconv .ParseFloat (s , bits ); err == nil {
if kind == reflect .Float32 {
*(*float32 )(p ) = float32 (f )
} else {
*(*float64 )(p ) = f
}
}
case reflect .Int , reflect .Int8 , reflect .Int16 , reflect .Int32 , reflect .Int64 :
var i int64
if i , err = strconv .ParseInt (s , 10 , intBits (kind )); err == nil {
switch kind {
case reflect .Int :
*(*int )(p ) = int (i )
case reflect .Int8 :
*(*int8 )(p ) = int8 (i )
case reflect .Int16 :
*(*int16 )(p ) = int16 (i )
case reflect .Int32 :
*(*int32 )(p ) = int32 (i )
default :
*(*int64 )(p ) = i
}
}
default :
var u uint64
if u , err = strconv .ParseUint (s , 10 , intBits (kind )); err == nil {
switch kind {
case reflect .Uint :
*(*uint )(p ) = uint (u )
case reflect .Uint8 :
*(*uint8 )(p ) = uint8 (u )
case reflect .Uint16 :
*(*uint16 )(p ) = uint16 (u )
case reflect .Uint32 :
*(*uint32 )(p ) = uint32 (u )
case reflect .Uintptr :
*(*uintptr )(p ) = uintptr (u )
default :
*(*uint64 )(p ) = u
}
}
}
if err != nil {
return stderrors .Unwrap (err )
}
return nil
}
func intBits(kind reflect .Kind ) int {
switch kind {
case reflect .Int8 , reflect .Uint8 :
return 8
case reflect .Int16 , reflect .Uint16 :
return 16
case reflect .Int32 , reflect .Uint32 :
return 32
case reflect .Int , reflect .Uint , reflect .Uintptr :
return strconv .IntSize
}
return 64
}
type v2InvalidDecoder struct {
typ reflect .Type
err error
}
func (d *v2InvalidDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
cursor = skipWhiteSpace (ctx .Buf , cursor )
if d .err == nil && ctx .Option .V2 &V2ReportErrorsWithLegacySemantics != 0 {
if ctx .Buf [cursor ] == 'n' {
return cursor + 4 , validateNull (ctx .Buf , cursor )
}
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor }
}
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor , NoKind : true , Err : d .err }
}
func (d *v2InvalidDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
type zeroer struct {
ptrType unsafe .Pointer
size uintptr
pointers bool
}
func newZeroer(typ reflect .Type ) zeroer {
return zeroer {ptrType : ptrTypeOf (typ ), size : typ .Size (), pointers : hasPointers (typ )}
}
func (z zeroer ) zero (p unsafe .Pointer ) {
if z .pointers {
valueAt (z .ptrType , p ).SetZero ()
return
}
clear (unsafe .Slice ((*byte )(p ), z .size ))
}
func hasPointers(typ reflect .Type ) bool {
switch typ .Kind () {
case reflect .Bool , 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 , reflect .Complex64 , reflect .Complex128 :
return false
case reflect .Array :
return typ .Len () > 0 && hasPointers (typ .Elem ())
case reflect .Struct :
for i := range typ .NumField () {
if hasPointers (typ .Field (i ).Type ) {
return true
}
}
return false
}
return true
}
func mergesInto(typ reflect .Type ) bool {
switch typ .Kind () {
case reflect .Ptr , reflect .Interface , reflect .Slice , reflect .Map , reflect .Struct :
return true
case reflect .Array :
return mergesInto (typ .Elem ())
}
return false
}
type v2SliceDecoder struct {
*sliceDecoder
zero bool
}
func newV2SliceDecoder(d *sliceDecoder ) *v2SliceDecoder {
return &v2SliceDecoder {sliceDecoder : d , zero : mergesInto (d .elemType )}
}
func (d *v2SliceDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
cursor = skipWhiteSpace (ctx .Buf , cursor )
if d .zero && ctx .Buf [cursor ] == '[' && (*sliceHeader )(p ).cap > 0 && ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
s := valueAt (d .slicePtrType , p )
s .Slice (0 , s .Cap ()).Clear ()
}
return d .sliceDecoder .Decode (ctx , cursor , depth , p )
}
func (c *compiler ) compileArrayV2 (typ reflect .Type , structName , fieldName string ) (Decoder , error ) {
d := &v2ArrayDecoder {typ : typ , array : newZeroer (typ ), elem : newZeroer (typ .Elem ()), alen : typ .Len ()}
dec , err := compileElem (typ , d , structName , fieldName , c )
if err != nil {
return nil , err
}
d .valueDecoder = c .goOnDecoder (dec )
return d , nil
}
type v2ArrayDecoder struct {
typ reflect .Type
valueDecoder Decoder
array zeroer
elem zeroer
alen int
}
func (d *v2ArrayDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
if ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
d .array .zero (p )
}
return cursor + 4 , nil
case '[' :
default :
return ctx .skipTypeError (cursor , depth , d .typ )
}
depth ++
if depth > maxDecodeNestingDepth {
return 0 , errors .ErrExceededMaxDepth (buf [cursor ], cursor )
}
cursor = skipWhiteSpace (buf , cursor +1 )
idx := 0
var lengthErr error
zeroElems := ctx .Option .V2 &V2MergeWithLegacySemantics == 0
if buf [cursor ] != ']' {
for {
if idx < d .alen {
ep := unsafe .Add (p , uintptr (idx )*d .elem .size )
if zeroElems {
d .elem .zero (ep )
}
c , err := d .valueDecoder .Decode (ctx , cursor , depth , ep )
if err != nil {
return 0 , err
}
cursor = c
} else {
c , err := ctx .skipValueV2 (cursor , depth )
if err != nil {
return 0 , err
}
cursor = c
lengthErr = errArrayOverflow
}
idx ++
cursor = skipWhiteSpace (buf , cursor )
if buf [cursor ] == ']' {
break
}
if buf [cursor ] != ',' {
return 0 , errors .ErrInvalidCharacter (buf [cursor ], "array" , cursor )
}
cursor = skipWhiteSpace (buf , cursor +1 )
}
}
for ; idx < d .alen ; idx ++ {
d .elem .zero (unsafe .Add (p , uintptr (idx )*d .elem .size ))
lengthErr = errArrayUnderflow
}
if lengthErr != nil && ctx .Option .V2 &V2UnmarshalArrayFromAnyLength == 0 {
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor , Err : lengthErr }
}
return cursor + 1 , nil
}
func (d *v2ArrayDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
type v2BytesDecoder struct {
typ reflect .Type
alen int
str *stringDecoder
}
func newV2BytesDecoder(typ reflect .Type ) *v2BytesDecoder {
d := &v2BytesDecoder {typ : typ , alen : -1 , str : newStringDecoder ("" , "" )}
if typ .Kind () == reflect .Array {
d .alen = typ .Len ()
}
return d
}
func (d *v2BytesDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
start := cursor
switch buf [cursor ] {
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
if d .alen < 0 {
*(*[]byte )(p ) = nil
} else if ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
clear (unsafe .Slice ((*byte )(p ), d .alen ))
}
return cursor + 4 , nil
case '"' :
default :
return ctx .skipTypeError (cursor , depth , d .typ )
}
text , end , err := d .str .decodeByte (buf , cursor )
if err != nil {
return 0 , err
}
var dst []byte
if d .alen < 0 {
dst = (*(*[]byte )(p ))[:0 ]
} else {
dst = unsafe .Slice ((*byte )(p ), d .alen )[:0 ]
}
b , err := base64 .StdEncoding .AppendDecode (dst , text )
if err == nil && len (text ) != base64 .StdEncoding .EncodedLen (len (b )) && ctx .Option .V2 &V2ParseBytesWithLooseRFC4648 == 0 {
i := bytes .IndexAny (text , "\r\n" )
err = fmt .Errorf ("illegal character %s at offset %d" , strconv .QuoteRune (rune (text [i ])), i )
}
if err == nil && d .alen >= 0 {
dst = dst [:d .alen ]
clear (dst [copy (dst , b ):])
if len (b ) != d .alen && ctx .Option .V2 &V2UnmarshalArrayFromAnyLength == 0 {
err = fmt .Errorf ("decoded length of %d mismatches array length of %d" , len (b ), d .alen )
}
}
if err != nil {
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : start , Err : err }
}
if d .alen < 0 {
if b == nil {
b = []byte {}
}
*(*[]byte )(p ) = b
}
return end , nil
}
func (d *v2BytesDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
type v2FormatBytesWithLegacySemanticsDecoder struct {
bytes *v2BytesDecoder
elements Decoder
}
func (d *v2FormatBytesWithLegacySemanticsDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
if ctx .Buf [skipWhiteSpace (ctx .Buf , cursor )] == '[' {
return d .elements .Decode (ctx , cursor , depth , p )
}
return d .bytes .Decode (ctx , cursor , depth , p )
}
func (d *v2FormatBytesWithLegacySemanticsDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
var anySliceType = reflect .TypeOf ([]any (nil ))
type v2InterfaceDecoder struct {
typ reflect .Type
ptrType unsafe .Pointer
empty bool
fast *interfaceDecoder
fromAny bool
}
var anyValueTypes = func () [256 ]reflect .Type {
var types [256 ]reflect .Type
types ['t' ], types ['f' ] = boolType , boolType
types ['"' ] = stringType
types ['-' ] = float64Type
for c := '0' ; c <= '9' ; c ++ {
types [c ] = float64Type
}
types ['{' ] = interfaceMapType
types ['[' ] = anySliceType
return types
}()
var boolType = reflect .TypeOf (false )
func (c *compiler ) newV2InterfaceDecoder (typ reflect .Type ) *v2InterfaceDecoder {
d := &v2InterfaceDecoder {
typ : typ , ptrType : ptrTypeOf (typ ), empty : typ .NumMethod () == 0 , fast : newEmptyInterfaceDecoder ("" , "" ),
}
for _ , t := range []reflect .Type {emptyInterfaceType , boolType , stringType , float64Type , interfaceMapType , anySliceType } {
d .fromAny = d .fromAny || len (c .funcs .funcsOf (t )) > 0
}
return d
}
func (d *v2InterfaceDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
if (*[2 ]unsafe .Pointer )(p )[0 ] != nil && ctx .Option .V2 &V2MergeWithLegacySemantics != 0 {
if !d .holdsPointer (p ) {
*(*[2 ]unsafe .Pointer )(p ) = [2 ]unsafe .Pointer {}
} else if buf [cursor ] == 'n' && runtime .TypeOfPtr (heldType (p , d .empty )).Elem ().Kind () == reflect .Pointer {
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
*(*unsafe .Pointer )(*interfaceData (p )) = nil
return cursor + 4 , nil
}
}
if buf [cursor ] == 'n' {
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
*(*[2 ]unsafe .Pointer )(p ) = [2 ]unsafe .Pointer {}
return cursor + 4 , nil
}
if (*[2 ]unsafe .Pointer )(p )[0 ] != nil {
return d .decodeHeld (ctx , cursor , depth , p )
}
if !d .empty {
return 0 , &errors .UnmarshalError {GoType : d .typ , Start : cursor , NoKind : true , Err : errNilInterface }
}
if d .fromAny {
return d .decodeByKind (ctx , cursor , depth , p )
}
next , err := d .fast .decodeEmptyInterface (ctx , cursor , depth , p )
reportErrors := ctx .Option .V2 &V2ReportErrorsWithLegacySemantics != 0
if (err != nil || ctx .typeError != nil && !reportErrors ) && ctx .Option .V2 &V2AllowDuplicateNames != 0 {
if c := buf [cursor ]; c == '{' || c == '[' {
if e := ctx .typeError ; e != nil && e .start >= cursor {
ctx .typeError = nil
}
*(*[2 ]unsafe .Pointer )(p ) = [2 ]unsafe .Pointer {}
return d .decodeMerging (ctx , cursor , depth , p )
}
}
if ctx .typeError != nil && !reportErrors {
return 0 , ctx .v2Error ()
}
if err != nil {
return 0 , err
}
if ctx .Option .V2 &V2AllowInvalidUTF8 == 0 && !validV2Text (buf [cursor :next ]) {
return 0 , errV2Text
}
return next , nil
}
func (d *v2InterfaceDecoder ) decodeByKind (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
typ := anyValueTypes [ctx .Buf [cursor ]]
if typ == nil {
return 0 , syntaxErrorAt (ctx .Buf , cursor , whereValue )
}
v := reflect .New (typ )
dec , err := ctx .DecoderOfV2 (runtime .TypePtr (v .Type ()))
if err != nil {
return 0 , err
}
next , err := dec .Decode (ctx , cursor , depth , v .UnsafePointer ())
valueAt (d .ptrType , p ).Set (v .Elem ())
return next , err
}
func (d *v2InterfaceDecoder ) decodeHeld (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
if typ := heldType (p , d .empty ); runtime .TypeOfPtr (typ ).Kind () == reflect .Pointer {
if ptr := *interfaceData (p ); ptr != nil && ctx .v2Funcs () == nil {
dec , err := ctx .DecoderOfV2 (typ )
if err != nil {
return 0 , err
}
return dec .Decode (ctx , cursor , depth , ptr )
}
dec , err := ctx .DecoderOfV2 (ptrTypeOf (runtime .TypeOfPtr (typ )))
if err != nil {
return 0 , err
}
return dec .Decode (ctx , cursor , depth , unsafe .Pointer (interfaceData (p )))
}
iface := valueAt (d .ptrType , p )
held := iface .Elem ()
if !d .fromAny && (held .Type () == interfaceMapType || held .Type () == anySliceType ) {
return d .decodeMerging (ctx , cursor , depth , p )
}
v := reflect .New (held .Type ())
v .Elem ().Set (held )
dec , err := ctx .DecoderOfV2 (runtime .TypePtr (v .Type ()))
if err != nil {
return 0 , err
}
next , err := dec .Decode (ctx , cursor , depth , v .UnsafePointer ())
iface .Set (v .Elem ())
return next , err
}
func (d *v2InterfaceDecoder ) holdsPointer (p unsafe .Pointer ) bool {
return runtime .TypeOfPtr (heldType (p , d .empty )).Kind () == reflect .Pointer && *interfaceData (p ) != nil
}
func heldType(p unsafe .Pointer , empty bool ) unsafe .Pointer {
typ := *(*unsafe .Pointer )(p )
if !empty {
typ = (*[2 ]unsafe .Pointer )(typ )[1 ]
}
return typ
}
func interfaceData(p unsafe .Pointer ) *unsafe .Pointer {
return &(*[2 ]unsafe .Pointer )(p )[1 ]
}
func (d *v2InterfaceDecoder ) decodeMerging (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
held := *(*any )(p )
switch buf [cursor ] {
case '{' :
m , ok := held .(map [string ]any )
if held != nil && !ok {
return ctx .skipTypeError (cursor , depth , reflect .TypeOf (held ))
}
if m == nil {
m = map [string ]any {}
*(*any )(p ) = m
}
return d .decodeObjectInto (ctx , cursor , depth , m )
case '[' :
s , ok := held .([]any )
if held != nil && !ok {
return ctx .skipTypeError (cursor , depth , reflect .TypeOf (held ))
}
next , err := d .decodeArrayInto (ctx , cursor , depth , &s )
*(*any )(p ) = s
return next , err
}
if held != nil {
return ctx .skipTypeError (cursor , depth , reflect .TypeOf (held ))
}
return d .Decode (ctx , cursor , depth , p )
}
func (d *v2InterfaceDecoder ) decodeElem (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
cursor = skipWhiteSpace (ctx .Buf , cursor )
var next int64
var err error
if c := ctx .Buf [cursor ]; (c == '{' || c == '[' ) && *(*any )(p ) == nil {
next , err = d .decodeMerging (ctx , cursor , depth , p )
} else {
next , err = d .Decode (ctx , cursor , depth , p )
}
if err != nil {
return ctx .goOnAfter (err , cursor , depth )
}
return next , nil
}
func (d *v2InterfaceDecoder ) decodeObjectInto (ctx *RuntimeContext , cursor , depth int64 , m map [string ]any ) (int64 , error ) {
buf := ctx .Buf
depth ++
if depth > maxDecodeNestingDepth {
return 0 , errors .ErrExceededMaxDepth (buf [cursor ], cursor )
}
cursor = skipWhiteSpace (buf , cursor +1 )
if buf [cursor ] == '}' {
return cursor + 1 , nil
}
var names nameSet
for {
if buf [cursor ] != '"' {
return 0 , syntaxErrorAt (buf , cursor , whereKey )
}
key , c , _ , err := d .fast .stringDecoder .decodeString (ctx , cursor )
if err != nil {
return 0 , err
}
if ctx .Option .V2 &V2AllowInvalidUTF8 == 0 && strings .IndexByte (key , 0xef ) >= 0 && !validV2Text (buf [cursor :c ]) {
return 0 , errV2Text
}
if ctx .Option .V2 &V2AllowDuplicateNames == 0 && !names .addCopy (ctx .V2Call (), nil , unsafeBytes (key )) {
return 0 , errV2Text
}
cursor = skipWhiteSpace (buf , c )
if buf [cursor ] != ':' {
return 0 , syntaxErrorAt (buf , cursor , whereAfterKey )
}
var value any
if ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
value = m [key ]
}
c , err = d .decodeElem (ctx , cursor +1 , depth , unsafe .Pointer (&value ))
m [key ] = value
if err != nil {
return 0 , err
}
cursor = skipWhiteSpace (buf , c )
switch buf [cursor ] {
case '}' :
names .end (ctx .v2 )
return cursor + 1 , nil
case ',' :
cursor = skipWhiteSpace (buf , cursor +1 )
default :
return 0 , syntaxErrorAt (buf , cursor , whereAfterPair )
}
}
}
func (d *v2InterfaceDecoder ) decodeArrayInto (ctx *RuntimeContext , cursor , depth int64 , s *[]any ) (int64 , error ) {
buf := ctx .Buf
depth ++
if depth > maxDecodeNestingDepth {
return 0 , errors .ErrExceededMaxDepth (buf [cursor ], cursor )
}
*s = (*s )[:0 ]
if *s == nil {
*s = []any {}
}
cursor = skipWhiteSpace (buf , cursor +1 )
if buf [cursor ] == ']' {
return cursor + 1 , nil
}
for {
*s = append (*s , nil )
c , err := d .decodeElem (ctx , cursor , depth , unsafe .Pointer (&(*s )[len (*s )-1 ]))
if err != nil {
return 0 , err
}
cursor = skipWhiteSpace (buf , c )
switch buf [cursor ] {
case ']' :
return cursor + 1 , nil
case ',' :
cursor ++
default :
return 0 , syntaxErrorAt (buf , cursor , whereAfterElement )
}
}
}
func (d *v2InterfaceDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
const maxListedNames = 32
type nameSet struct {
first, n, copies int
mask nameMask
set map [string ]struct {}
}
type nameMask [4 ]uint64
func (m *nameMask ) bit (h uint64 ) (*uint64 , uint64 ) {
return &m [h >>62 ], uint64 (1 ) << (h >> 56 & 63 )
}
const maxWordsName = 16
func (s *nameSet ) add (call *V2Call , buf []byte , start , end int64 ) bool {
return s .insert (call , buf , buf [start :end ], start )
}
func (s *nameSet ) addListed (call *V2Call , buf []byte , start , end int64 ) bool {
n := end - start
if n > maxWordsName || start +maxWordsName > int64 (cap (buf )) || s .set != nil || s .n >= maxListedNames {
return false
}
a , b := inputNameWords (buf , start , n )
h := mixNameWords (a , b , n )
t := &call .names
entries := t .entries
w , bit := s .mask .bit (h )
if *w &bit != 0 || len (entries ) >= cap (entries ) {
return false
}
*w |= bit
if s .n == 0 {
s .first , s .copies = len (entries ), len (t .copies )
}
entries = entries [:len (entries )+1 ]
entries [len (entries )-1 ] = nameEntry {hash : h , at : start , n : n }
(*sliceHeader )(unsafe .Pointer (&t .entries )).len = len (entries )
s .n ++
return true
}
func inputNameWords(buf []byte , at , n int64 ) (uint64 , uint64 ) {
a , b := load64 (buf , at ), uint64 (0 )
if n < 8 {
a &= 1 <<(uint (n )*8 &63 ) - 1
} else if n > 8 {
b = load64 (buf , at +n -8 )
}
return a , b
}
func (s *nameSet ) addCopy (call *V2Call , buf , name []byte ) bool {
return s .insert (call , buf , name , -1 )
}
func (s *nameSet ) insert (call *V2Call , buf , name []byte , at int64 ) bool {
t := &call .names
if s .n == 0 {
s .first , s .copies = len (t .entries ), len (t .copies )
}
var h uint64
if n := int64 (len (name )); at >= 0 && n <= maxWordsName && at +maxWordsName <= int64 (cap (buf )) {
a , b := inputNameWords (buf , at , n )
h = mixNameWords (a , b , n )
} else {
h = nameHash (name )
}
if s .set != nil {
if _ , exists := s .set [unsafeString (name )]; exists {
return false
}
} else if w , bit := s .mask .bit (h ); *w &bit == 0 {
*w |= bit
} else {
for i := range t .entries [s .first :] {
if e := &t .entries [s .first +i ]; e .hash == h && e .n == int64 (len (name )) && string (t .name (e , buf )) == string (name ) {
return false
}
}
}
if at < 0 {
at = -1 - int64 (len (t .copies ))
t .copies = append (t .copies , name ...)
}
t .entries = append (t .entries , nameEntry {hash : h , at : at , n : int64 (len (name ))})
s .n ++
switch {
case s .set != nil :
s .set [unsafeString (t .name (&t .entries [len (t .entries )-1 ], buf ))] = struct {}{}
case s .n > maxListedNames :
s .set = make (map [string ]struct {}, 2 *s .n )
for i := range t .entries [s .first :] {
s .set [unsafeString (t .name (&t .entries [s .first +i ], buf ))] = struct {}{}
}
}
return true
}
func (s *nameSet ) end (call *V2Call ) {
if s .n != 0 {
call .names .truncate (s .first , s .copies )
s .set = nil
}
}
func unsafeString(b []byte ) string { return unsafe .String (unsafe .SliceData (b ), len (b )) }
func unsafeBytes(s string ) []byte { return unsafe .Slice (unsafe .StringData (s ), len (s )) }
func nameHash(name []byte ) uint64 {
n := len (name )
var a , b uint64
if n >= 8 {
a = binary .LittleEndian .Uint64 (name )
if n > 8 {
b = binary .LittleEndian .Uint64 (name [n -8 :])
for i := 8 ; i < n -8 ; i += 8 {
a = (a ^ binary .LittleEndian .Uint64 (name [i :])) * 0x9E3779B97F4A7C15
}
}
} else {
switch {
case n >= 4 :
a = uint64 (binary .LittleEndian .Uint32 (name )) | uint64 (binary .LittleEndian .Uint32 (name [n -4 :]))>>(8 *(8 -n ))<<32
case n >= 2 :
a = uint64 (binary .LittleEndian .Uint16 (name )) | uint64 (binary .LittleEndian .Uint16 (name [n -2 :]))>>(8 *(4 -n ))<<16
case n == 1 :
a = uint64 (name [0 ])
}
}
return mixNameWords (a , b , int64 (n ))
}
func mixNameWords(a , b uint64 , n int64 ) uint64 {
h := (a ^ bits .RotateLeft64 (b , 29 ) ^ uint64 (n )<<58 ) * 0x9E3779B97F4A7C15
return h ^ h >>31
}
type callNames struct {
entries []nameEntry
copies []byte
}
type nameEntry struct {
hash uint64
at int64
n int64
}
func (t *callNames ) name (e *nameEntry , buf []byte ) []byte {
if e .at < 0 {
at := -1 - e .at
return t .copies [at : at +e .n ]
}
return buf [e .at : e .at +e .n ]
}
func (t *callNames ) mark () (int , int ) { return len (t .entries ), len (t .copies ) }
func (t *callNames ) truncate (entries , copies int ) {
const large = 64 << 10
if entries == 0 && (cap (t .copies ) > large || cap (t .entries ) > large /int (unsafe .Sizeof (nameEntry {}))) {
*t = callNames {}
return
}
t .entries = t .entries [:entries ]
t .copies = t .copies [:copies ]
}
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 .