Debian Codegraph @

vendor/github.com/ugorji/go/codec/helper.go

raw
1 // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
2 // Use of this source code is governed by a MIT license found in the LICENSE file.
3
4 package codec
5
6 // Contains code shared by both encode and decode.
7
8 // Some shared ideas around encoding/decoding
9 // ------------------------------------------
10 //
11 // If an interface{} is passed, we first do a type assertion to see if it is
12 // a primitive type or a map/slice of primitive types, and use a fastpath to handle it.
13 //
14 // If we start with a reflect.Value, we are already in reflect.Value land and
15 // will try to grab the function for the underlying Type and directly call that function.
16 // This is more performant than calling reflect.Value.Interface().
17 //
18 // This still helps us bypass many layers of reflection, and give best performance.
19 //
20 // Containers
21 // ------------
22 // Containers in the stream are either associative arrays (key-value pairs) or
23 // regular arrays (indexed by incrementing integers).
24 //
25 // Some streams support indefinite-length containers, and use a breaking
26 // byte-sequence to denote that the container has come to an end.
27 //
28 // Some streams also are text-based, and use explicit separators to denote the
29 // end/beginning of different values.
30 //
31 // During encode, we use a high-level condition to determine how to iterate through
32 // the container. That decision is based on whether the container is text-based (with
33 // separators) or binary (without separators). If binary, we do not even call the
34 // encoding of separators.
35 //
36 // During decode, we use a different high-level condition to determine how to iterate
37 // through the containers. That decision is based on whether the stream contained
38 // a length prefix, or if it used explicit breaks. If length-prefixed, we assume that
39 // it has to be binary, and we do not even try to read separators.
40 //
41 // Philosophy
42 // ------------
43 // On decode, this codec will update containers appropriately:
44 // - If struct, update fields from stream into fields of struct.
45 // If field in stream not found in struct, handle appropriately (based on option).
46 // If a struct field has no corresponding value in the stream, leave it AS IS.
47 // If nil in stream, set value to nil/zero value.
48 // - If map, update map from stream.
49 // If the stream value is NIL, set the map to nil.
50 // - if slice, try to update up to length of array in stream.
51 // if container len is less than stream array length,
52 // and container cannot be expanded, handled (based on option).
53 // This means you can decode 4-element stream array into 1-element array.
54 //
55 // ------------------------------------
56 // On encode, user can specify omitEmpty. This means that the value will be omitted
57 // if the zero value. The problem may occur during decode, where omitted values do not affect
58 // the value being decoded into. This means that if decoding into a struct with an
59 // int field with current value=5, and the field is omitted in the stream, then after
60 // decoding, the value will still be 5 (not 0).
61 // omitEmpty only works if you guarantee that you always decode into zero-values.
62 //
63 // ------------------------------------
64 // We could have truncated a map to remove keys not available in the stream,
65 // or set values in the struct which are not in the stream to their zero values.
66 // We decided against it because there is no efficient way to do it.
67 // We may introduce it as an option later.
68 // However, that will require enabling it for both runtime and code generation modes.
69 //
70 // To support truncate, we need to do 2 passes over the container:
71 // map
72 // - first collect all keys (e.g. in k1)
73 // - for each key in stream, mark k1 that the key should not be removed
74 // - after updating map, do second pass and call delete for all keys in k1 which are not marked
75 // struct:
76 // - for each field, track the *typeInfo s1
77 // - iterate through all s1, and for each one not marked, set value to zero
78 // - this involves checking the possible anonymous fields which are nil ptrs.
79 // too much work.
80 //
81 // ------------------------------------------
82 // Error Handling is done within the library using panic.
83 //
84 // This way, the code doesn't have to keep checking if an error has happened,
85 // and we don't have to keep sending the error value along with each call
86 // or storing it in the En|Decoder and checking it constantly along the way.
87 //
88 // The disadvantage is that small functions which use panics cannot be inlined.
89 // The code accounts for that by only using panics behind an interface;
90 // since interface calls cannot be inlined, this is irrelevant.
91 //
92 // We considered storing the error is En|Decoder.
93 // - once it has its err field set, it cannot be used again.
94 // - panicing will be optional, controlled by const flag.
95 // - code should always check error first and return early.
96 // We eventually decided against it as it makes the code clumsier to always
97 // check for these error conditions.
98
99 import (
100 "bytes"
101 "encoding"
102 "encoding/binary"
103 "errors"
104 "fmt"
105 "math"
106 "os"
107 "reflect"
108 "sort"
109 "strconv"
110 "strings"
111 "sync"
112 "time"
113 )
114
115 const (
116 scratchByteArrayLen = 32
117 // initCollectionCap = 16 // 32 is defensive. 16 is preferred.
118
119 // Support encoding.(Binary|Text)(Unm|M)arshaler.
120 // This constant flag will enable or disable it.
121 supportMarshalInterfaces = true
122
123 // for debugging, set this to false, to catch panic traces.
124 // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
125 recoverPanicToErr = true
126
127 // arrayCacheLen is the length of the cache used in encoder or decoder for
128 // allowing zero-alloc initialization.
129 arrayCacheLen = 8
130
131 // We tried an optimization, where we detect if a type is one of the known types
132 // we optimized for (e.g. int, []uint64, etc).
133 //
134 // However, we notice some worse performance when using this optimization.
135 // So we hide it behind a flag, to turn on if needed.
136 useLookupRecognizedTypes = false
137
138 // using recognized allows us to do d.decode(interface{}) instead of d.decodeValue(reflect.Value)
139 // when we can infer that the kind of the interface{} is one of the ones hard-coded in the
140 // type switch for known types or the ones defined by fast-path.
141 //
142 // However, it seems we get better performance when we don't recognize, and just let
143 // reflection handle it.
144 //
145 // Reasoning is as below:
146 // typeswitch is a binary search with a branch to a code-point.
147 // getdecfn is a binary search with a call to a function pointer.
148 //
149 // both are about the same.
150 //
151 // so: why prefer typeswitch?
152 //
153 // is recognized does the following:
154 // - lookup rtid
155 // - check if in sorted list
156 // - calls decode(type switch)
157 // - 1 or 2 binary search to a point in code
158 // - branch there
159 //
160 // vs getdecfn
161 // - lookup rtid
162 // - check in sorted list for a function pointer
163 // - calls it to decode using reflection (optimized)
164
165 // always set xDebug = false before releasing software
166 xDebug = true
167 )
168
169 var (
170 oneByteArr = [1]byte{0}
171 zeroByteSlice = oneByteArr[:0:0]
172 )
173
174 var pool pooler
175
176 func init() {
177 pool.init()
178 }
179
180 // type findCodecFnMode uint8
181
182 // const (
183 // findCodecFnModeMap findCodecFnMode = iota
184 // findCodecFnModeBinarySearch
185 // findCodecFnModeLinearSearch
186 // )
187
188 type charEncoding uint8
189
190 const (
191 c_RAW charEncoding = iota
192 c_UTF8
193 c_UTF16LE
194 c_UTF16BE
195 c_UTF32LE
196 c_UTF32BE
197 )
198
199 // valueType is the stream type
200 type valueType uint8
201
202 const (
203 valueTypeUnset valueType = iota
204 valueTypeNil
205 valueTypeInt
206 valueTypeUint
207 valueTypeFloat
208 valueTypeBool
209 valueTypeString
210 valueTypeSymbol
211 valueTypeBytes
212 valueTypeMap
213 valueTypeArray
214 valueTypeTimestamp
215 valueTypeExt
216
217 // valueTypeInvalid = 0xff
218 )
219
220 func (x valueType) String() string {
221 switch x {
222 case valueTypeNil:
223 return "Nil"
224 case valueTypeInt:
225 return "Int"
226 case valueTypeUint:
227 return "Uint"
228 case valueTypeFloat:
229 return "Float"
230 case valueTypeBool:
231 return "Bool"
232 case valueTypeString:
233 return "String"
234 case valueTypeSymbol:
235 return "Symbol"
236 case valueTypeBytes:
237 return "Bytes"
238 case valueTypeMap:
239 return "Map"
240 case valueTypeArray:
241 return "Array"
242 case valueTypeTimestamp:
243 return "Timestamp"
244 case valueTypeExt:
245 return "Ext"
246 }
247 return strconv.FormatInt(int64(x), 10)
248 }
249
250 type seqType uint8
251
252 const (
253 _ seqType = iota
254 seqTypeArray
255 seqTypeSlice
256 seqTypeChan
257 )
258
259 // note that containerMapStart and containerArraySend are not sent.
260 // This is because the ReadXXXStart and EncodeXXXStart already does these.
261 type containerState uint8
262
263 const (
264 _ containerState = iota
265
266 containerMapStart // slot left open, since Driver method already covers it
267 containerMapKey
268 containerMapValue
269 containerMapEnd
270 containerArrayStart // slot left open, since Driver methods already cover it
271 containerArrayElem
272 containerArrayEnd
273 )
274
275 // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
276 type sfiIdx struct {
277 name string
278 index int
279 }
280
281 // do not recurse if a containing type refers to an embedded type
282 // which refers back to its containing type (via a pointer).
283 // The second time this back-reference happens, break out,
284 // so as not to cause an infinite loop.
285 const rgetMaxRecursion = 2
286
287 // Anecdotally, we believe most types have <= 12 fields.
288 // Java's PMD rules set TooManyFields threshold to 15.
289 const typeInfoLoadArrayLen = 12
290
291 type typeInfoLoad struct {
292 fNames []string
293 encNames []string
294 etypes []uintptr
295 sfis []*structFieldInfo
296 }
297
298 type typeInfoLoadArray struct {
299 fNames [typeInfoLoadArrayLen]string
300 encNames [typeInfoLoadArrayLen]string
301 etypes [typeInfoLoadArrayLen]uintptr
302 sfis [typeInfoLoadArrayLen]*structFieldInfo
303 sfiidx [typeInfoLoadArrayLen]sfiIdx
304 }
305
306 // type containerStateRecv interface {
307 // sendContainerState(containerState)
308 // }
309
310 // mirror json.Marshaler and json.Unmarshaler here,
311 // so we don't import the encoding/json package
312 type jsonMarshaler interface {
313 MarshalJSON() ([]byte, error)
314 }
315 type jsonUnmarshaler interface {
316 UnmarshalJSON([]byte) error
317 }
318
319 // type byteAccepter func(byte) bool
320
321 var (
322 bigen = binary.BigEndian
323 structInfoFieldName = "_struct"
324
325 mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
326 mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
327 intfSliceTyp = reflect.TypeOf([]interface{}(nil))
328 intfTyp = intfSliceTyp.Elem()
329
330 stringTyp = reflect.TypeOf("")
331 timeTyp = reflect.TypeOf(time.Time{})
332 rawExtTyp = reflect.TypeOf(RawExt{})
333 rawTyp = reflect.TypeOf(Raw{})
334 uint8SliceTyp = reflect.TypeOf([]uint8(nil))
335
336 mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
337
338 binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
339 binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
340
341 textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
342 textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
343
344 jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
345 jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
346
347 selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
348
349 uint8SliceTypId = rt2id(uint8SliceTyp)
350 rawExtTypId = rt2id(rawExtTyp)
351 rawTypId = rt2id(rawTyp)
352 intfTypId = rt2id(intfTyp)
353 timeTypId = rt2id(timeTyp)
354 stringTypId = rt2id(stringTyp)
355
356 mapStrIntfTypId = rt2id(mapStrIntfTyp)
357 mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
358 intfSliceTypId = rt2id(intfSliceTyp)
359 // mapBySliceTypId = rt2id(mapBySliceTyp)
360
361 intBitsize uint8 = uint8(reflect.TypeOf(int(0)).Bits())
362 uintBitsize uint8 = uint8(reflect.TypeOf(uint(0)).Bits())
363
364 bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
365 bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
366
367 chkOvf checkOverflow
368
369 noFieldNameToStructFieldInfoErr = errors.New("no field name passed to parseStructFieldInfo")
370 )
371
372 var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
373
374 var immutableKindsSet = [32]bool{
375 // reflect.Invalid: ,
376 reflect.Bool: true,
377 reflect.Int: true,
378 reflect.Int8: true,
379 reflect.Int16: true,
380 reflect.Int32: true,
381 reflect.Int64: true,
382 reflect.Uint: true,
383 reflect.Uint8: true,
384 reflect.Uint16: true,
385 reflect.Uint32: true,
386 reflect.Uint64: true,
387 reflect.Uintptr: true,
388 reflect.Float32: true,
389 reflect.Float64: true,
390 reflect.Complex64: true,
391 reflect.Complex128: true,
392 // reflect.Array
393 // reflect.Chan
394 // reflect.Func: true,
395 // reflect.Interface
396 // reflect.Map
397 // reflect.Ptr
398 // reflect.Slice
399 reflect.String: true,
400 // reflect.Struct
401 // reflect.UnsafePointer
402 }
403
404 var recognizedRtids []uintptr
405 var recognizedRtidPtrs []uintptr
406 var recognizedRtidOrPtrs []uintptr
407
408 func init() {
409 if !useLookupRecognizedTypes {
410 return
411 }
412 for _, v := range [...]interface{}{
413 float32(0),
414 float64(0),
415 uintptr(0),
416 uint(0),
417 uint8(0),
418 uint16(0),
419 uint32(0),
420 uint64(0),
421 uintptr(0),
422 int(0),
423 int8(0),
424 int16(0),
425 int32(0),
426 int64(0),
427 bool(false),
428 string(""),
429 Raw{},
430 []byte(nil),
431 } {
432 rt := reflect.TypeOf(v)
433 recognizedRtids = append(recognizedRtids, rt2id(rt))
434 recognizedRtidPtrs = append(recognizedRtidPtrs, rt2id(reflect.PtrTo(rt)))
435 }
436 }
437
438 func containsU(s []uintptr, v uintptr) bool {
439 // return false // TODO: REMOVE
440 h, i, j := 0, 0, len(s)
441 for i < j {
442 h = i + (j-i)/2
443 if s[h] < v {
444 i = h + 1
445 } else {
446 j = h
447 }
448 }
449 if i < len(s) && s[i] == v {
450 return true
451 }
452 return false
453 }
454
455 func isRecognizedRtid(rtid uintptr) bool {
456 return containsU(recognizedRtids, rtid)
457 }
458
459 func isRecognizedRtidPtr(rtid uintptr) bool {
460 return containsU(recognizedRtidPtrs, rtid)
461 }
462
463 func isRecognizedRtidOrPtr(rtid uintptr) bool {
464 return containsU(recognizedRtidOrPtrs, rtid)
465 }
466
467 // Selfer defines methods by which a value can encode or decode itself.
468 //
469 // Any type which implements Selfer will be able to encode or decode itself.
470 // Consequently, during (en|de)code, this takes precedence over
471 // (text|binary)(M|Unm)arshal or extension support.
472 type Selfer interface {
473 CodecEncodeSelf(*Encoder)
474 CodecDecodeSelf(*Decoder)
475 }
476
477 // MapBySlice represents a slice which should be encoded as a map in the stream.
478 // The slice contains a sequence of key-value pairs.
479 // This affords storing a map in a specific sequence in the stream.
480 //
481 // The support of MapBySlice affords the following:
482 // - A slice type which implements MapBySlice will be encoded as a map
483 // - A slice can be decoded from a map in the stream
484 type MapBySlice interface {
485 MapBySlice()
486 }
487
488 // WARNING: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
489 //
490 // BasicHandle encapsulates the common options and extension functions.
491 type BasicHandle struct {
492 // TypeInfos is used to get the type info for any type.
493 //
494 // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
495 TypeInfos *TypeInfos
496
497 extHandle
498 EncodeOptions
499 DecodeOptions
500 noBuiltInTypeChecker
501 }
502
503 func (x *BasicHandle) getBasicHandle() *BasicHandle {
504 return x
505 }
506
507 func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
508 if x.TypeInfos == nil {
509 return defTypeInfos.get(rtid, rt)
510 }
511 return x.TypeInfos.get(rtid, rt)
512 }
513
514 // Handle is the interface for a specific encoding format.
515 //
516 // Typically, a Handle is pre-configured before first time use,
517 // and not modified while in use. Such a pre-configured Handle
518 // is safe for concurrent access.
519 type Handle interface {
520 getBasicHandle() *BasicHandle
521 newEncDriver(w *Encoder) encDriver
522 newDecDriver(r *Decoder) decDriver
523 isBinary() bool
524 hasElemSeparators() bool
525 IsBuiltinType(rtid uintptr) bool
526 }
527
528 // Raw represents raw formatted bytes.
529 // We "blindly" store it during encode and store the raw bytes during decode.
530 // Note: it is dangerous during encode, so we may gate the behaviour behind an Encode flag which must be explicitly set.
531 type Raw []byte
532
533 // RawExt represents raw unprocessed extension data.
534 // Some codecs will decode extension data as a *RawExt if there is no registered extension for the tag.
535 //
536 // Only one of Data or Value is nil. If Data is nil, then the content of the RawExt is in the Value.
537 type RawExt struct {
538 Tag uint64
539 // Data is the []byte which represents the raw ext. If Data is nil, ext is exposed in Value.
540 // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types
541 Data []byte
542 // Value represents the extension, if Data is nil.
543 // Value is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
544 Value interface{}
545 }
546
547 // BytesExt handles custom (de)serialization of types to/from []byte.
548 // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
549 type BytesExt interface {
550 // WriteExt converts a value to a []byte.
551 //
552 // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
553 WriteExt(v interface{}) []byte
554
555 // ReadExt updates a value from a []byte.
556 ReadExt(dst interface{}, src []byte)
557 }
558
559 // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
560 // The Encoder or Decoder will then handle the further (de)serialization of that known type.
561 //
562 // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
563 type InterfaceExt interface {
564 // ConvertExt converts a value into a simpler interface for easy encoding e.g. convert time.Time to int64.
565 //
566 // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
567 ConvertExt(v interface{}) interface{}
568
569 // UpdateExt updates a value from a simpler interface for easy decoding e.g. convert int64 to time.Time.
570 UpdateExt(dst interface{}, src interface{})
571 }
572
573 // Ext handles custom (de)serialization of custom types / extensions.
574 type Ext interface {
575 BytesExt
576 InterfaceExt
577 }
578
579 // addExtWrapper is a wrapper implementation to support former AddExt exported method.
580 type addExtWrapper struct {
581 encFn func(reflect.Value) ([]byte, error)
582 decFn func(reflect.Value, []byte) error
583 }
584
585 func (x addExtWrapper) WriteExt(v interface{}) []byte {
586 bs, err := x.encFn(reflect.ValueOf(v))
587 if err != nil {
588 panic(err)
589 }
590 return bs
591 }
592
593 func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
594 if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
595 panic(err)
596 }
597 }
598
599 func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
600 return x.WriteExt(v)
601 }
602
603 func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
604 x.ReadExt(dest, v.([]byte))
605 }
606
607 type setExtWrapper struct {
608 b BytesExt
609 i InterfaceExt
610 }
611
612 func (x *setExtWrapper) WriteExt(v interface{}) []byte {
613 if x.b == nil {
614 panic("BytesExt.WriteExt is not supported")
615 }
616 return x.b.WriteExt(v)
617 }
618
619 func (x *setExtWrapper) ReadExt(v interface{}, bs []byte) {
620 if x.b == nil {
621 panic("BytesExt.WriteExt is not supported")
622
623 }
624 x.b.ReadExt(v, bs)
625 }
626
627 func (x *setExtWrapper) ConvertExt(v interface{}) interface{} {
628 if x.i == nil {
629 panic("InterfaceExt.ConvertExt is not supported")
630
631 }
632 return x.i.ConvertExt(v)
633 }
634
635 func (x *setExtWrapper) UpdateExt(dest interface{}, v interface{}) {
636 if x.i == nil {
637 panic("InterfaceExxt.UpdateExt is not supported")
638
639 }
640 x.i.UpdateExt(dest, v)
641 }
642
643 type binaryEncodingType struct{}
644
645 func (_ binaryEncodingType) isBinary() bool { return true }
646
647 type textEncodingType struct{}
648
649 func (_ textEncodingType) isBinary() bool { return false }
650
651 // noBuiltInTypes is embedded into many types which do not support builtins
652 // e.g. msgpack, simple, cbor.
653
654 type noBuiltInTypeChecker struct{}
655
656 func (_ noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
657
658 type noBuiltInTypes struct{ noBuiltInTypeChecker }
659
660 func (_ noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
661 func (_ noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
662
663 // type noStreamingCodec struct{}
664 // func (_ noStreamingCodec) CheckBreak() bool { return false }
665 // func (_ noStreamingCodec) hasElemSeparators() bool { return false }
666
667 type noElemSeparators struct{}
668
669 func (_ noElemSeparators) hasElemSeparators() (v bool) { return }
670
671 // bigenHelper.
672 // Users must already slice the x completely, because we will not reslice.
673 type bigenHelper struct {
674 x []byte // must be correctly sliced to appropriate len. slicing is a cost.
675 w encWriter
676 }
677
678 func (z bigenHelper) writeUint16(v uint16) {
679 bigen.PutUint16(z.x, v)
680 z.w.writeb(z.x)
681 }
682
683 func (z bigenHelper) writeUint32(v uint32) {
684 bigen.PutUint32(z.x, v)
685 z.w.writeb(z.x)
686 }
687
688 func (z bigenHelper) writeUint64(v uint64) {
689 bigen.PutUint64(z.x, v)
690 z.w.writeb(z.x)
691 }
692
693 type extTypeTagFn struct {
694 rtid uintptr
695 rt reflect.Type
696 tag uint64
697 ext Ext
698 }
699
700 type extHandle []extTypeTagFn
701
702 // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
703 //
704 // AddExt registes an encode and decode function for a reflect.Type.
705 // AddExt internally calls SetExt.
706 // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
707 func (o *extHandle) AddExt(
708 rt reflect.Type, tag byte,
709 encfn func(reflect.Value) ([]byte, error), decfn func(reflect.Value, []byte) error,
710 ) (err error) {
711 if encfn == nil || decfn == nil {
712 return o.SetExt(rt, uint64(tag), nil)
713 }
714 return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
715 }
716
717 // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
718 //
719 // Note that the type must be a named type, and specifically not
720 // a pointer or Interface. An error is returned if that is not honored.
721 //
722 // To Deregister an ext, call SetExt with nil Ext
723 func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
724 // o is a pointer, because we may need to initialize it
725 if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
726 err = fmt.Errorf("codec.Handle.AddExt: Takes named type, not a pointer or interface: %T",
727 reflect.Zero(rt).Interface())
728 return
729 }
730
731 rtid := rt2id(rt)
732 for _, v := range *o {
733 if v.rtid == rtid {
734 v.tag, v.ext = tag, ext
735 return
736 }
737 }
738
739 if *o == nil {
740 *o = make([]extTypeTagFn, 0, 4)
741 }
742 *o = append(*o, extTypeTagFn{rtid, rt, tag, ext})
743 return
744 }
745
746 func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
747 var v *extTypeTagFn
748 for i := range o {
749 v = &o[i]
750 if v.rtid == rtid {
751 return v
752 }
753 }
754 return nil
755 }
756
757 func (o extHandle) getExtForTag(tag uint64) *extTypeTagFn {
758 var v *extTypeTagFn
759 for i := range o {
760 v = &o[i]
761 if v.tag == tag {
762 return v
763 }
764 }
765 return nil
766 }
767
768 const maxLevelsEmbedding = 16
769
770 type structFieldInfo struct {
771 encName string // encode name
772 fieldName string // field name
773
774 is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
775 nis uint8 // num levels of embedding. if 1, then it's not embedded.
776 omitEmpty bool
777 toArray bool // if field is _struct, is the toArray set?
778 }
779
780 func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
781 if v, valid := si.field(v, false); valid {
782 v.Set(reflect.Zero(v.Type()))
783 }
784 }
785
786 // rv returns the field of the struct.
787 // If anonymous, it returns an Invalid
788 func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
789 // replicate FieldByIndex
790 for i, x := range si.is {
791 if uint8(i) == si.nis {
792 break
793 }
794 if v, valid = baseStructRv(v, update); !valid {
795 return
796 }
797 v = v.Field(int(x))
798 }
799
800 return v, true
801 }
802
803 func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
804 v, _ = si.field(v, update)
805 return v
806 }
807
808 func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
809 // if fname == "" {
810 // panic(noFieldNameToStructFieldInfoErr)
811 // }
812 si := structFieldInfo{
813 encName: fname,
814 }
815
816 if stag != "" {
817 for i, s := range strings.Split(stag, ",") {
818 if i == 0 {
819 if s != "" {
820 si.encName = s
821 }
822 } else {
823 if s == "omitempty" {
824 si.omitEmpty = true
825 } else if s == "toarray" {
826 si.toArray = true
827 }
828 }
829 }
830 }
831 // si.encNameBs = []byte(si.encName)
832 return &si
833 }
834
835 type sfiSortedByEncName []*structFieldInfo
836
837 func (p sfiSortedByEncName) Len() int {
838 return len(p)
839 }
840
841 func (p sfiSortedByEncName) Less(i, j int) bool {
842 return p[i].encName < p[j].encName
843 }
844
845 func (p sfiSortedByEncName) Swap(i, j int) {
846 p[i], p[j] = p[j], p[i]
847 }
848
849 const structFieldNodeNumToCache = 4
850
851 type structFieldNodeCache struct {
852 rv [structFieldNodeNumToCache]reflect.Value
853 idx [structFieldNodeNumToCache]uint32
854 num uint8
855 }
856
857 func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
858 // defer func() { fmt.Printf(">>>> found in cache2? %v\n", valid) }()
859 for i, k := range &x.idx {
860 if uint8(i) == x.num {
861 return // break
862 }
863 if key == k {
864 return x.rv[i], true
865 }
866 }
867 return
868 }
869
870 func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
871 if x.num < structFieldNodeNumToCache {
872 x.rv[x.num] = fv
873 x.idx[x.num] = key
874 x.num++
875 return
876 }
877 }
878
879 type structFieldNode struct {
880 v reflect.Value
881 cache2 structFieldNodeCache
882 cache3 structFieldNodeCache
883 update bool
884 }
885
886 func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
887 // return si.fieldval(x.v, x.update)
888 // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
889 // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
890 var valid bool
891 switch si.nis {
892 case 1:
893 fv = x.v.Field(int(si.is[0]))
894 case 2:
895 if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
896 fv = fv.Field(int(si.is[1]))
897 return
898 }
899 fv = x.v.Field(int(si.is[0]))
900 if fv, valid = baseStructRv(fv, x.update); !valid {
901 return
902 }
903 x.cache2.tryAdd(fv, uint32(si.is[0]))
904 fv = fv.Field(int(si.is[1]))
905 case 3:
906 var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
907 if fv, valid = x.cache3.get(key); valid {
908 fv = fv.Field(int(si.is[2]))
909 return
910 }
911 fv = x.v.Field(int(si.is[0]))
912 if fv, valid = baseStructRv(fv, x.update); !valid {
913 return
914 }
915 fv = fv.Field(int(si.is[1]))
916 if fv, valid = baseStructRv(fv, x.update); !valid {
917 return
918 }
919 x.cache3.tryAdd(fv, key)
920 fv = fv.Field(int(si.is[2]))
921 default:
922 fv, _ = si.field(x.v, x.update)
923 }
924 return
925 }
926
927 func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
928 for v.Kind() == reflect.Ptr {
929 if v.IsNil() {
930 if !update {
931 return
932 }
933 v.Set(reflect.New(v.Type().Elem()))
934 }
935 v = v.Elem()
936 }
937 return v, true
938 }
939
940 // typeInfo keeps information about each type referenced in the encode/decode sequence.
941 //
942 // During an encode/decode sequence, we work as below:
943 // - If base is a built in type, en/decode base value
944 // - If base is registered as an extension, en/decode base value
945 // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
946 // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
947 // - Else decode appropriately based on the reflect.Kind
948 type typeInfo struct {
949 sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
950 sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
951
952 rt reflect.Type
953 rtid uintptr
954 // rv0 reflect.Value // saved zero value, used if immutableKind
955
956 numMeth uint16 // number of methods
957
958 // baseId gives pointer to the base reflect.Type, after deferencing
959 // the pointers. E.g. base type of ***time.Time is time.Time.
960 base reflect.Type
961 baseId uintptr
962 baseIndir int8 // number of indirections to get to base
963
964 anyOmitEmpty bool
965
966 mbs bool // base type (T or *T) is a MapBySlice
967
968 bm bool // base type (T or *T) is a binaryMarshaler
969 bunm bool // base type (T or *T) is a binaryUnmarshaler
970 bmIndir int8 // number of indirections to get to binaryMarshaler type
971 bunmIndir int8 // number of indirections to get to binaryUnmarshaler type
972
973 tm bool // base type (T or *T) is a textMarshaler
974 tunm bool // base type (T or *T) is a textUnmarshaler
975 tmIndir int8 // number of indirections to get to textMarshaler type
976 tunmIndir int8 // number of indirections to get to textUnmarshaler type
977
978 jm bool // base type (T or *T) is a jsonMarshaler
979 junm bool // base type (T or *T) is a jsonUnmarshaler
980 jmIndir int8 // number of indirections to get to jsonMarshaler type
981 junmIndir int8 // number of indirections to get to jsonUnmarshaler type
982
983 cs bool // base type (T or *T) is a Selfer
984 csIndir int8 // number of indirections to get to Selfer type
985
986 toArray bool // whether this (struct) type should be encoded as an array
987 }
988
989 // define length beyond which we do a binary search instead of a linear search.
990 // From our testing, linear search seems faster than binary search up to 16-field structs.
991 // However, we set to 8 similar to what python does for hashtables.
992 const indexForEncNameBinarySearchThreshold = 8
993
994 func (ti *typeInfo) indexForEncName(name string) int {
995 // NOTE: name may be a stringView, so don't pass it to another function.
996 //tisfi := ti.sfi
997 sfilen := len(ti.sfi)
998 if sfilen < indexForEncNameBinarySearchThreshold {
999 for i, si := range ti.sfi {
1000 if si.encName == name {
1001 return i
1002 }
1003 }
1004 return -1
1005 }
1006 // binary search. adapted from sort/search.go.
1007 h, i, j := 0, 0, sfilen
1008 for i < j {
1009 h = i + (j-i)/2
1010 if ti.sfi[h].encName < name {
1011 i = h + 1
1012 } else {
1013 j = h
1014 }
1015 }
1016 if i < sfilen && ti.sfi[i].encName == name {
1017 return i
1018 }
1019 return -1
1020 }
1021
1022 type rtid2ti struct {
1023 rtid uintptr
1024 ti *typeInfo
1025 }
1026
1027 // TypeInfos caches typeInfo for each type on first inspection.
1028 //
1029 // It is configured with a set of tag keys, which are used to get
1030 // configuration for the type.
1031 type TypeInfos struct {
1032 infos atomicTypeInfoSlice // formerly map[uintptr]*typeInfo, now *[]rtid2ti
1033 mu sync.Mutex
1034 tags []string
1035 }
1036
1037 // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
1038 //
1039 // This allows users customize the struct tag keys which contain configuration
1040 // of their types.
1041 func NewTypeInfos(tags []string) *TypeInfos {
1042 return &TypeInfos{tags: tags}
1043 }
1044
1045 func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
1046 // check for tags: codec, json, in that order.
1047 // this allows seamless support for many configured structs.
1048 for _, x := range x.tags {
1049 s = t.Get(x)
1050 if s != "" {
1051 return s
1052 }
1053 }
1054 return
1055 }
1056
1057 func (x *TypeInfos) find(sp *[]rtid2ti, rtid uintptr) (idx int, ti *typeInfo) {
1058 // binary search. adapted from sort/search.go.
1059 // if sp == nil {
1060 // return -1, nil
1061 // }
1062 s := *sp
1063 h, i, j := 0, 0, len(s)
1064 for i < j {
1065 h = i + (j-i)/2
1066 if s[h].rtid < rtid {
1067 i = h + 1
1068 } else {
1069 j = h
1070 }
1071 }
1072 if i < len(s) && s[i].rtid == rtid {
1073 return i, s[i].ti
1074 }
1075 return i, nil
1076 }
1077
1078 func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
1079 sp := x.infos.load()
1080 var idx int
1081 if sp != nil {
1082 idx, pti = x.find(sp, rtid)
1083 if pti != nil {
1084 return
1085 }
1086 }
1087
1088 // do not hold lock while computing this.
1089 // it may lead to duplication, but that's ok.
1090 ti := typeInfo{rt: rt, rtid: rtid}
1091 // ti.rv0 = reflect.Zero(rt)
1092
1093 ti.numMeth = uint16(rt.NumMethod())
1094 var ok bool
1095 var indir int8
1096 if ok, indir = implementsIntf(rt, binaryMarshalerTyp); ok {
1097 ti.bm, ti.bmIndir = true, indir
1098 }
1099 if ok, indir = implementsIntf(rt, binaryUnmarshalerTyp); ok {
1100 ti.bunm, ti.bunmIndir = true, indir
1101 }
1102 if ok, indir = implementsIntf(rt, textMarshalerTyp); ok {
1103 ti.tm, ti.tmIndir = true, indir
1104 }
1105 if ok, indir = implementsIntf(rt, textUnmarshalerTyp); ok {
1106 ti.tunm, ti.tunmIndir = true, indir
1107 }
1108 if ok, indir = implementsIntf(rt, jsonMarshalerTyp); ok {
1109 ti.jm, ti.jmIndir = true, indir
1110 }
1111 if ok, indir = implementsIntf(rt, jsonUnmarshalerTyp); ok {
1112 ti.junm, ti.junmIndir = true, indir
1113 }
1114 if ok, indir = implementsIntf(rt, selferTyp); ok {
1115 ti.cs, ti.csIndir = true, indir
1116 }
1117 if ok, _ = implementsIntf(rt, mapBySliceTyp); ok {
1118 ti.mbs = true
1119 }
1120
1121 pt := rt
1122 var ptIndir int8
1123 // for ; pt.Kind() == reflect.Ptr; pt, ptIndir = pt.Elem(), ptIndir+1 { }
1124 for pt.Kind() == reflect.Ptr {
1125 pt = pt.Elem()
1126 ptIndir++
1127 }
1128 if ptIndir == 0 {
1129 ti.base = rt
1130 ti.baseId = rtid
1131 } else {
1132 ti.base = pt
1133 ti.baseId = rt2id(pt)
1134 ti.baseIndir = ptIndir
1135 }
1136
1137 if rt.Kind() == reflect.Struct {
1138 var omitEmpty bool
1139 if f, ok := rt.FieldByName(structInfoFieldName); ok {
1140 siInfo := parseStructFieldInfo(structInfoFieldName, x.structTag(f.Tag))
1141 ti.toArray = siInfo.toArray
1142 omitEmpty = siInfo.omitEmpty
1143 }
1144 pp, pi := pool.tiLoad()
1145 pv := pi.(*typeInfoLoadArray)
1146 pv.etypes[0] = ti.baseId
1147 vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
1148 x.rget(rt, rtid, omitEmpty, nil, &vv)
1149 ti.sfip, ti.sfi, ti.anyOmitEmpty = rgetResolveSFI(vv.sfis, pv.sfiidx[:0])
1150 pp.Put(pi)
1151 }
1152 // sfi = sfip
1153
1154 var vs []rtid2ti
1155 x.mu.Lock()
1156 sp = x.infos.load()
1157 if sp == nil {
1158 pti = &ti
1159 vs = []rtid2ti{{rtid, pti}}
1160 x.infos.store(&vs)
1161 } else {
1162 idx, pti = x.find(sp, rtid)
1163 if pti == nil {
1164 s := *sp
1165 pti = &ti
1166 vs = make([]rtid2ti, len(s)+1)
1167 copy(vs, s[:idx])
1168 vs[idx] = rtid2ti{rtid, pti}
1169 copy(vs[idx+1:], s[idx:])
1170 x.infos.store(&vs)
1171 }
1172 }
1173 x.mu.Unlock()
1174 return
1175 }
1176
1177 func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
1178 indexstack []uint16, pv *typeInfoLoad,
1179 ) {
1180 // Read up fields and store how to access the value.
1181 //
1182 // It uses go's rules for message selectors,
1183 // which say that the field with the shallowest depth is selected.
1184 //
1185 // Note: we consciously use slices, not a map, to simulate a set.
1186 // Typically, types have < 16 fields,
1187 // and iteration using equals is faster than maps there
1188 flen := rt.NumField()
1189 if flen > (1<<maxLevelsEmbedding - 1) {
1190 panic(fmt.Errorf("codec: types with more than %v fields are not supported - has %v fields", (1<<maxLevelsEmbedding - 1), flen))
1191 }
1192 LOOP:
1193 for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
1194 f := rt.Field(int(j))
1195 fkind := f.Type.Kind()
1196 // skip if a func type, or is unexported, or structTag value == "-"
1197 switch fkind {
1198 case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
1199 continue LOOP
1200 }
1201
1202 // if r1, _ := utf8.DecodeRuneInString(f.Name);
1203 // r1 == utf8.RuneError || !unicode.IsUpper(r1) {
1204 if f.PkgPath != "" && !f.Anonymous { // unexported, not embedded
1205 continue
1206 }
1207 stag := x.structTag(f.Tag)
1208 if stag == "-" {
1209 continue
1210 }
1211 var si *structFieldInfo
1212 // if anonymous and no struct tag (or it's blank),
1213 // and a struct (or pointer to struct), inline it.
1214 if f.Anonymous && fkind != reflect.Interface {
1215 doInline := stag == ""
1216 if !doInline {
1217 si = parseStructFieldInfo("", stag)
1218 doInline = si.encName == ""
1219 // doInline = si.isZero()
1220 }
1221 if doInline {
1222 ft := f.Type
1223 for ft.Kind() == reflect.Ptr {
1224 ft = ft.Elem()
1225 }
1226 if ft.Kind() == reflect.Struct {
1227 // if etypes contains this, don't call rget again (as fields are already seen here)
1228 ftid := rt2id(ft)
1229 // We cannot recurse forever, but we need to track other field depths.
1230 // So - we break if we see a type twice (not the first time).
1231 // This should be sufficient to handle an embedded type that refers to its
1232 // owning type, which then refers to its embedded type.
1233 processIt := true
1234 numk := 0
1235 for _, k := range pv.etypes {
1236 if k == ftid {
1237 numk++
1238 if numk == rgetMaxRecursion {
1239 processIt = false
1240 break
1241 }
1242 }
1243 }
1244 if processIt {
1245 pv.etypes = append(pv.etypes, ftid)
1246 indexstack2 := make([]uint16, len(indexstack)+1)
1247 copy(indexstack2, indexstack)
1248 indexstack2[len(indexstack)] = j
1249 // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
1250 x.rget(ft, ftid, omitEmpty, indexstack2, pv)
1251 }
1252 continue
1253 }
1254 }
1255 }
1256
1257 // after the anonymous dance: if an unexported field, skip
1258 if f.PkgPath != "" { // unexported
1259 continue
1260 }
1261
1262 if f.Name == "" {
1263 panic(noFieldNameToStructFieldInfoErr)
1264 }
1265
1266 pv.fNames = append(pv.fNames, f.Name)
1267
1268 if si == nil {
1269 si = parseStructFieldInfo(f.Name, stag)
1270 } else if si.encName == "" {
1271 si.encName = f.Name
1272 }
1273 si.fieldName = f.Name
1274
1275 pv.encNames = append(pv.encNames, si.encName)
1276
1277 // si.ikind = int(f.Type.Kind())
1278 if len(indexstack) > maxLevelsEmbedding-1 {
1279 panic(fmt.Errorf("codec: only supports up to %v depth of embedding - type has %v depth", maxLevelsEmbedding-1, len(indexstack)))
1280 }
1281 si.nis = uint8(len(indexstack)) + 1
1282 copy(si.is[:], indexstack)
1283 si.is[len(indexstack)] = j
1284
1285 if omitEmpty {
1286 si.omitEmpty = true
1287 }
1288 pv.sfis = append(pv.sfis, si)
1289 }
1290 }
1291
1292 // resolves the struct field info got from a call to rget.
1293 // Returns a trimmed, unsorted and sorted []*structFieldInfo.
1294 func rgetResolveSFI(x []*structFieldInfo, pv []sfiIdx) (y, z []*structFieldInfo, anyOmitEmpty bool) {
1295 var n int
1296 for i, v := range x {
1297 xn := v.encName // TODO: fieldName or encName? use encName for now.
1298 var found bool
1299 for j, k := range pv {
1300 if k.name == xn {
1301 // one of them must be reset to nil, and the index updated appropriately to the other one
1302 if v.nis == x[k.index].nis {
1303 } else if v.nis < x[k.index].nis {
1304 pv[j].index = i
1305 if x[k.index] != nil {
1306 x[k.index] = nil
1307 n++
1308 }
1309 } else {
1310 if x[i] != nil {
1311 x[i] = nil
1312 n++
1313 }
1314 }
1315 found = true
1316 break
1317 }
1318 }
1319 if !found {
1320 pv = append(pv, sfiIdx{xn, i})
1321 }
1322 }
1323
1324 // remove all the nils
1325 y = make([]*structFieldInfo, len(x)-n)
1326 n = 0
1327 for _, v := range x {
1328 if v == nil {
1329 continue
1330 }
1331 if !anyOmitEmpty && v.omitEmpty {
1332 anyOmitEmpty = true
1333 }
1334 y[n] = v
1335 n++
1336 }
1337
1338 z = make([]*structFieldInfo, len(y))
1339 copy(z, y)
1340 sort.Sort(sfiSortedByEncName(z))
1341 return
1342 }
1343
1344 func xprintf(format string, a ...interface{}) {
1345 if xDebug {
1346 fmt.Fprintf(os.Stderr, format, a...)
1347 }
1348 }
1349
1350 func panicToErr(err *error) {
1351 if recoverPanicToErr {
1352 if x := recover(); x != nil {
1353 // if false && xDebug {
1354 // fmt.Printf("panic'ing with: %v\n", x)
1355 // debug.PrintStack()
1356 // }
1357 panicValToErr(x, err)
1358 }
1359 }
1360 }
1361
1362 func panicToErrs2(err1, err2 *error) {
1363 if recoverPanicToErr {
1364 if x := recover(); x != nil {
1365 panicValToErr(x, err1)
1366 panicValToErr(x, err2)
1367 }
1368 }
1369 }
1370
1371 // func doPanic(tag string, format string, params ...interface{}) {
1372 // params2 := make([]interface{}, len(params)+1)
1373 // params2[0] = tag
1374 // copy(params2[1:], params)
1375 // panic(fmt.Errorf("%s: "+format, params2...))
1376 // }
1377
1378 func isImmutableKind(k reflect.Kind) (v bool) {
1379 return immutableKindsSet[k]
1380 // return false ||
1381 // k == reflect.Int ||
1382 // k == reflect.Int8 ||
1383 // k == reflect.Int16 ||
1384 // k == reflect.Int32 ||
1385 // k == reflect.Int64 ||
1386 // k == reflect.Uint ||
1387 // k == reflect.Uint8 ||
1388 // k == reflect.Uint16 ||
1389 // k == reflect.Uint32 ||
1390 // k == reflect.Uint64 ||
1391 // k == reflect.Uintptr ||
1392 // k == reflect.Float32 ||
1393 // k == reflect.Float64 ||
1394 // k == reflect.Bool ||
1395 // k == reflect.String
1396 }
1397
1398 // ----
1399
1400 type codecFnInfo struct {
1401 ti *typeInfo
1402 xfFn Ext
1403 xfTag uint64
1404 seq seqType
1405 addr bool
1406 }
1407
1408 // codecFn encapsulates the captured variables and the encode function.
1409 // This way, we only do some calculations one times, and pass to the
1410 // code block that should be called (encapsulated in a function)
1411 // instead of executing the checks every time.
1412 type codecFn struct {
1413 i codecFnInfo
1414 fe func(*Encoder, *codecFnInfo, reflect.Value)
1415 fd func(*Decoder, *codecFnInfo, reflect.Value)
1416 }
1417
1418 type codecRtidFn struct {
1419 rtid uintptr
1420 fn codecFn
1421 }
1422
1423 type codecFner struct {
1424 hh Handle
1425 h *BasicHandle
1426 cs [arrayCacheLen]*[arrayCacheLen]codecRtidFn
1427 s []*[arrayCacheLen]codecRtidFn
1428 sn uint32
1429 be bool
1430 js bool
1431 cf [arrayCacheLen]codecRtidFn
1432 }
1433
1434 func (c *codecFner) reset(hh Handle) {
1435 c.hh = hh
1436 c.h = hh.getBasicHandle()
1437 _, c.js = hh.(*JsonHandle)
1438 c.be = hh.isBinary()
1439 }
1440
1441 func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
1442 rtid := rt2id(rt)
1443 var j uint32
1444 var sn uint32 = c.sn
1445 if sn == 0 {
1446 c.s = c.cs[:1]
1447 c.s[0] = &c.cf
1448 c.cf[0].rtid = rtid
1449 fn = &(c.cf[0].fn)
1450 c.sn = 1
1451 } else {
1452 LOOP1:
1453 for _, x := range c.s {
1454 for i := range x {
1455 if j == sn {
1456 break LOOP1
1457 }
1458 if x[i].rtid == rtid {
1459 fn = &(x[i].fn)
1460 return
1461 }
1462 j++
1463 }
1464 }
1465 sx, sy := sn/arrayCacheLen, sn%arrayCacheLen
1466 if sy == 0 {
1467 c.s = append(c.s, &[arrayCacheLen]codecRtidFn{})
1468 }
1469 c.s[sx][sy].rtid = rtid
1470 fn = &(c.s[sx][sy].fn)
1471 c.sn++
1472 }
1473
1474 ti := c.h.getTypeInfo(rtid, rt)
1475 fi := &(fn.i)
1476 fi.ti = ti
1477
1478 if checkCodecSelfer && ti.cs {
1479 fn.fe = (*Encoder).selferMarshal
1480 fn.fd = (*Decoder).selferUnmarshal
1481 } else if rtid == rawTypId {
1482 fn.fe = (*Encoder).raw
1483 fn.fd = (*Decoder).raw
1484 } else if rtid == rawExtTypId {
1485 fn.fe = (*Encoder).rawExt
1486 fn.fd = (*Decoder).rawExt
1487 fn.i.addr = true
1488 } else if c.hh.IsBuiltinType(rtid) {
1489 fn.fe = (*Encoder).builtin
1490 fn.fd = (*Decoder).builtin
1491 fn.i.addr = true
1492 } else if xfFn := c.h.getExt(rtid); xfFn != nil {
1493 fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
1494 fn.fe = (*Encoder).ext
1495 fn.fd = (*Decoder).ext
1496 fn.i.addr = true
1497 } else if supportMarshalInterfaces && c.be && ti.bm {
1498 fn.fe = (*Encoder).binaryMarshal
1499 fn.fd = (*Decoder).binaryUnmarshal
1500 } else if supportMarshalInterfaces && !c.be && c.js && ti.jm {
1501 //If JSON, we should check JSONMarshal before textMarshal
1502 fn.fe = (*Encoder).jsonMarshal
1503 fn.fd = (*Decoder).jsonUnmarshal
1504 } else if supportMarshalInterfaces && !c.be && ti.tm {
1505 fn.fe = (*Encoder).textMarshal
1506 fn.fd = (*Decoder).textUnmarshal
1507 } else {
1508 rk := rt.Kind()
1509 if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
1510 if rt.PkgPath() == "" { // un-named slice or map
1511 if idx := fastpathAV.index(rtid); idx != -1 {
1512 fn.fe = fastpathAV[idx].encfn
1513 fn.fd = fastpathAV[idx].decfn
1514 fn.i.addr = true
1515 }
1516 } else {
1517 // use mapping for underlying type if there
1518 var rtu reflect.Type
1519 if rk == reflect.Map {
1520 rtu = reflect.MapOf(rt.Key(), rt.Elem())
1521 } else {
1522 rtu = reflect.SliceOf(rt.Elem())
1523 }
1524 rtuid := rt2id(rtu)
1525 if idx := fastpathAV.index(rtuid); idx != -1 {
1526 xfnf := fastpathAV[idx].encfn
1527 xrt := fastpathAV[idx].rt
1528 fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
1529 xfnf(e, xf, xrv.Convert(xrt))
1530 }
1531 fn.i.addr = true
1532 xfnf2 := fastpathAV[idx].decfn
1533 fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
1534 xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
1535 }
1536 }
1537 }
1538 }
1539 if fn.fe == nil && fn.fd == nil {
1540 switch rk {
1541 case reflect.Bool:
1542 fn.fe = (*Encoder).kBool
1543 fn.fd = (*Decoder).kBool
1544 case reflect.String:
1545 fn.fe = (*Encoder).kString
1546 fn.fd = (*Decoder).kString
1547 case reflect.Int:
1548 fn.fd = (*Decoder).kInt
1549 fn.fe = (*Encoder).kInt
1550 case reflect.Int8:
1551 fn.fe = (*Encoder).kInt
1552 fn.fd = (*Decoder).kInt8
1553 case reflect.Int16:
1554 fn.fe = (*Encoder).kInt
1555 fn.fd = (*Decoder).kInt16
1556 case reflect.Int32:
1557 fn.fe = (*Encoder).kInt
1558 fn.fd = (*Decoder).kInt32
1559 case reflect.Int64:
1560 fn.fe = (*Encoder).kInt
1561 fn.fd = (*Decoder).kInt64
1562 case reflect.Uint:
1563 fn.fd = (*Decoder).kUint
1564 fn.fe = (*Encoder).kUint
1565 case reflect.Uint8:
1566 fn.fe = (*Encoder).kUint
1567 fn.fd = (*Decoder).kUint8
1568 case reflect.Uint16:
1569 fn.fe = (*Encoder).kUint
1570 fn.fd = (*Decoder).kUint16
1571 case reflect.Uint32:
1572 fn.fe = (*Encoder).kUint
1573 fn.fd = (*Decoder).kUint32
1574 case reflect.Uint64:
1575 fn.fe = (*Encoder).kUint
1576 fn.fd = (*Decoder).kUint64
1577 // case reflect.Ptr:
1578 // fn.fd = (*Decoder).kPtr
1579 case reflect.Uintptr:
1580 fn.fe = (*Encoder).kUint
1581 fn.fd = (*Decoder).kUintptr
1582 case reflect.Float32:
1583 fn.fe = (*Encoder).kFloat32
1584 fn.fd = (*Decoder).kFloat32
1585 case reflect.Float64:
1586 fn.fe = (*Encoder).kFloat64
1587 fn.fd = (*Decoder).kFloat64
1588 case reflect.Invalid:
1589 fn.fe = (*Encoder).kInvalid
1590 case reflect.Chan:
1591 fi.seq = seqTypeChan
1592 fn.fe = (*Encoder).kSlice
1593 fn.fd = (*Decoder).kSlice
1594 case reflect.Slice:
1595 fi.seq = seqTypeSlice
1596 fn.fe = (*Encoder).kSlice
1597 fn.fd = (*Decoder).kSlice
1598 case reflect.Array:
1599 fi.seq = seqTypeArray
1600 fn.fe = (*Encoder).kSlice
1601 fi.addr = false
1602 rt2 := reflect.SliceOf(rt.Elem())
1603 fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
1604 // println(">>>>>> decoding an array ... ")
1605 d.cf.get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
1606 // println(">>>>>> decoding an array ... DONE")
1607 }
1608 // fn.fd = (*Decoder).kArray
1609 case reflect.Struct:
1610 if ti.anyOmitEmpty {
1611 fn.fe = (*Encoder).kStruct
1612 } else {
1613 fn.fe = (*Encoder).kStructNoOmitempty
1614 }
1615 fn.fd = (*Decoder).kStruct
1616 // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
1617 // case reflect.Ptr:
1618 // fn.fe = (*Encoder).kPtr
1619 // case reflect.Interface:
1620 // fn.fe = (*Encoder).kInterface
1621 case reflect.Map:
1622 fn.fe = (*Encoder).kMap
1623 fn.fd = (*Decoder).kMap
1624 case reflect.Interface:
1625 // encode: reflect.Interface are handled already by preEncodeValue
1626 fn.fd = (*Decoder).kInterface
1627 default:
1628 fn.fe = (*Encoder).kErr
1629 fn.fd = (*Decoder).kErr
1630 }
1631 }
1632 }
1633
1634 return
1635 }
1636
1637 // ----
1638
1639 // these functions must be inlinable, and not call anybody
1640 type checkOverflow struct{}
1641
1642 func (_ checkOverflow) Float32(f float64) (overflow bool) {
1643 if f < 0 {
1644 f = -f
1645 }
1646 return math.MaxFloat32 < f && f <= math.MaxFloat64
1647 }
1648
1649 func (_ checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
1650 if bitsize == 0 || bitsize >= 64 || v == 0 {
1651 return
1652 }
1653 if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
1654 overflow = true
1655 }
1656 return
1657 }
1658
1659 func (_ checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
1660 if bitsize == 0 || bitsize >= 64 || v == 0 {
1661 return
1662 }
1663 if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
1664 overflow = true
1665 }
1666 return
1667 }
1668
1669 func (_ checkOverflow) SignedInt(v uint64) (i int64, overflow bool) {
1670 //e.g. -127 to 128 for int8
1671 pos := (v >> 63) == 0
1672 ui2 := v & 0x7fffffffffffffff
1673 if pos {
1674 if ui2 > math.MaxInt64 {
1675 overflow = true
1676 return
1677 }
1678 } else {
1679 if ui2 > math.MaxInt64-1 {
1680 overflow = true
1681 return
1682 }
1683 }
1684 i = int64(v)
1685 return
1686 }
1687
1688 // ------------------ SORT -----------------
1689
1690 func isNaN(f float64) bool { return f != f }
1691
1692 // -----------------------
1693
1694 type intSlice []int64
1695 type uintSlice []uint64
1696 type uintptrSlice []uintptr
1697 type floatSlice []float64
1698 type boolSlice []bool
1699 type stringSlice []string
1700 type bytesSlice [][]byte
1701
1702 func (p intSlice) Len() int { return len(p) }
1703 func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
1704 func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1705
1706 func (p uintSlice) Len() int { return len(p) }
1707 func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
1708 func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1709
1710 func (p uintptrSlice) Len() int { return len(p) }
1711 func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] }
1712 func (p uintptrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1713
1714 func (p floatSlice) Len() int { return len(p) }
1715 func (p floatSlice) Less(i, j int) bool {
1716 return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
1717 }
1718 func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1719
1720 func (p stringSlice) Len() int { return len(p) }
1721 func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
1722 func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1723
1724 func (p bytesSlice) Len() int { return len(p) }
1725 func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
1726 func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1727
1728 func (p boolSlice) Len() int { return len(p) }
1729 func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
1730 func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1731
1732 // ---------------------
1733
1734 type intRv struct {
1735 v int64
1736 r reflect.Value
1737 }
1738 type intRvSlice []intRv
1739 type uintRv struct {
1740 v uint64
1741 r reflect.Value
1742 }
1743 type uintRvSlice []uintRv
1744 type floatRv struct {
1745 v float64
1746 r reflect.Value
1747 }
1748 type floatRvSlice []floatRv
1749 type boolRv struct {
1750 v bool
1751 r reflect.Value
1752 }
1753 type boolRvSlice []boolRv
1754 type stringRv struct {
1755 v string
1756 r reflect.Value
1757 }
1758 type stringRvSlice []stringRv
1759 type bytesRv struct {
1760 v []byte
1761 r reflect.Value
1762 }
1763 type bytesRvSlice []bytesRv
1764
1765 func (p intRvSlice) Len() int { return len(p) }
1766 func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
1767 func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1768
1769 func (p uintRvSlice) Len() int { return len(p) }
1770 func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
1771 func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1772
1773 func (p floatRvSlice) Len() int { return len(p) }
1774 func (p floatRvSlice) Less(i, j int) bool {
1775 return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
1776 }
1777 func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1778
1779 func (p stringRvSlice) Len() int { return len(p) }
1780 func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
1781 func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1782
1783 func (p bytesRvSlice) Len() int { return len(p) }
1784 func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
1785 func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1786
1787 func (p boolRvSlice) Len() int { return len(p) }
1788 func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
1789 func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1790
1791 // -----------------
1792
1793 type bytesI struct {
1794 v []byte
1795 i interface{}
1796 }
1797
1798 type bytesISlice []bytesI
1799
1800 func (p bytesISlice) Len() int { return len(p) }
1801 func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
1802 func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
1803
1804 // -----------------
1805
1806 type set []uintptr
1807
1808 func (s *set) add(v uintptr) (exists bool) {
1809 // e.ci is always nil, or len >= 1
1810 x := *s
1811 if x == nil {
1812 x = make([]uintptr, 1, 8)
1813 x[0] = v
1814 *s = x
1815 return
1816 }
1817 // typically, length will be 1. make this perform.
1818 if len(x) == 1 {
1819 if j := x[0]; j == 0 {
1820 x[0] = v
1821 } else if j == v {
1822 exists = true
1823 } else {
1824 x = append(x, v)
1825 *s = x
1826 }
1827 return
1828 }
1829 // check if it exists
1830 for _, j := range x {
1831 if j == v {
1832 exists = true
1833 return
1834 }
1835 }
1836 // try to replace a "deleted" slot
1837 for i, j := range x {
1838 if j == 0 {
1839 x[i] = v
1840 return
1841 }
1842 }
1843 // if unable to replace deleted slot, just append it.
1844 x = append(x, v)
1845 *s = x
1846 return
1847 }
1848
1849 func (s *set) remove(v uintptr) (exists bool) {
1850 x := *s
1851 if len(x) == 0 {
1852 return
1853 }
1854 if len(x) == 1 {
1855 if x[0] == v {
1856 x[0] = 0
1857 }
1858 return
1859 }
1860 for i, j := range x {
1861 if j == v {
1862 exists = true
1863 x[i] = 0 // set it to 0, as way to delete it.
1864 // copy(x[i:], x[i+1:])
1865 // x = x[:len(x)-1]
1866 return
1867 }
1868 }
1869 return
1870 }
1871
1872 // ------
1873
1874 // bitset types are better than [256]bool, because they permit the whole
1875 // bitset array being on a single cache line and use less memory.
1876
1877 // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
1878 // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
1879
1880 type bitset256 [32]byte
1881
1882 func (x *bitset256) set(pos byte) {
1883 x[pos>>3] |= (1 << (pos & 7))
1884 }
1885 func (x *bitset256) unset(pos byte) {
1886 x[pos>>3] &^= (1 << (pos & 7))
1887 }
1888 func (x *bitset256) isset(pos byte) bool {
1889 return x[pos>>3]&(1<<(pos&7)) != 0
1890 }
1891
1892 type bitset128 [16]byte
1893
1894 func (x *bitset128) set(pos byte) {
1895 x[pos>>3] |= (1 << (pos & 7))
1896 }
1897 func (x *bitset128) unset(pos byte) {
1898 x[pos>>3] &^= (1 << (pos & 7))
1899 }
1900 func (x *bitset128) isset(pos byte) bool {
1901 return x[pos>>3]&(1<<(pos&7)) != 0
1902 }
1903
1904 // ------------
1905
1906 type pooler struct {
1907 // for stringRV
1908 strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool
1909 // for the decNaked
1910 dn sync.Pool
1911 tiload sync.Pool
1912 }
1913
1914 func (p *pooler) init() {
1915 p.strRv8.New = func() interface{} { return new([8]stringRv) }
1916 p.strRv16.New = func() interface{} { return new([16]stringRv) }
1917 p.strRv32.New = func() interface{} { return new([32]stringRv) }
1918 p.strRv64.New = func() interface{} { return new([64]stringRv) }
1919 p.strRv128.New = func() interface{} { return new([128]stringRv) }
1920 p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
1921 p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
1922 }
1923
1924 func (p *pooler) stringRv8() (sp *sync.Pool, v interface{}) {
1925 return &p.strRv8, p.strRv8.Get()
1926 }
1927 func (p *pooler) stringRv16() (sp *sync.Pool, v interface{}) {
1928 return &p.strRv16, p.strRv16.Get()
1929 }
1930 func (p *pooler) stringRv32() (sp *sync.Pool, v interface{}) {
1931 return &p.strRv32, p.strRv32.Get()
1932 }
1933 func (p *pooler) stringRv64() (sp *sync.Pool, v interface{}) {
1934 return &p.strRv64, p.strRv64.Get()
1935 }
1936 func (p *pooler) stringRv128() (sp *sync.Pool, v interface{}) {
1937 return &p.strRv128, p.strRv128.Get()
1938 }
1939 func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
1940 return &p.dn, p.dn.Get()
1941 }
1942 func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
1943 return &p.tiload, p.tiload.Get()
1944 }