OSDN Git Service

feat(warder): add warder backbone (#181)
[bytom/vapor.git] / vendor / github.com / ugorji / go / codec / helper.go
1 // Copyright (c) 2012-2018 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         "io"
106         "math"
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         // size of the cacheline: defaulting to value for archs: amd64, arm64, 386
132         // should use "runtime/internal/sys".CacheLineSize, but that is not exposed.
133         cacheLineSize = 64
134
135         wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize
136         wordSize     = wordSizeBits / 8
137
138         maxLevelsEmbedding = 14 // use this, so structFieldInfo fits into 8 bytes
139 )
140
141 var (
142         oneByteArr    = [1]byte{0}
143         zeroByteSlice = oneByteArr[:0:0]
144 )
145
146 var codecgen bool
147
148 var refBitset bitset32
149 var pool pooler
150 var panicv panicHdl
151
152 func init() {
153         pool.init()
154
155         refBitset.set(byte(reflect.Map))
156         refBitset.set(byte(reflect.Ptr))
157         refBitset.set(byte(reflect.Func))
158         refBitset.set(byte(reflect.Chan))
159 }
160
161 type clsErr struct {
162         closed    bool  // is it closed?
163         errClosed error // error on closing
164 }
165
166 type charEncoding uint8
167
168 const (
169         cRAW charEncoding = iota
170         cUTF8
171         cUTF16LE
172         cUTF16BE
173         cUTF32LE
174         cUTF32BE
175 )
176
177 // valueType is the stream type
178 type valueType uint8
179
180 const (
181         valueTypeUnset valueType = iota
182         valueTypeNil
183         valueTypeInt
184         valueTypeUint
185         valueTypeFloat
186         valueTypeBool
187         valueTypeString
188         valueTypeSymbol
189         valueTypeBytes
190         valueTypeMap
191         valueTypeArray
192         valueTypeTime
193         valueTypeExt
194
195         // valueTypeInvalid = 0xff
196 )
197
198 var valueTypeStrings = [...]string{
199         "Unset",
200         "Nil",
201         "Int",
202         "Uint",
203         "Float",
204         "Bool",
205         "String",
206         "Symbol",
207         "Bytes",
208         "Map",
209         "Array",
210         "Timestamp",
211         "Ext",
212 }
213
214 func (x valueType) String() string {
215         if int(x) < len(valueTypeStrings) {
216                 return valueTypeStrings[x]
217         }
218         return strconv.FormatInt(int64(x), 10)
219 }
220
221 type seqType uint8
222
223 const (
224         _ seqType = iota
225         seqTypeArray
226         seqTypeSlice
227         seqTypeChan
228 )
229
230 // note that containerMapStart and containerArraySend are not sent.
231 // This is because the ReadXXXStart and EncodeXXXStart already does these.
232 type containerState uint8
233
234 const (
235         _ containerState = iota
236
237         containerMapStart // slot left open, since Driver method already covers it
238         containerMapKey
239         containerMapValue
240         containerMapEnd
241         containerArrayStart // slot left open, since Driver methods already cover it
242         containerArrayElem
243         containerArrayEnd
244 )
245
246 // // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
247 // type sfiIdx struct {
248 //      name  string
249 //      index int
250 // }
251
252 // do not recurse if a containing type refers to an embedded type
253 // which refers back to its containing type (via a pointer).
254 // The second time this back-reference happens, break out,
255 // so as not to cause an infinite loop.
256 const rgetMaxRecursion = 2
257
258 // Anecdotally, we believe most types have <= 12 fields.
259 // - even Java's PMD rules set TooManyFields threshold to 15.
260 // However, go has embedded fields, which should be regarded as
261 // top level, allowing structs to possibly double or triple.
262 // In addition, we don't want to keep creating transient arrays,
263 // especially for the sfi index tracking, and the evtypes tracking.
264 //
265 // So - try to keep typeInfoLoadArray within 2K bytes
266 const (
267         typeInfoLoadArraySfisLen   = 16
268         typeInfoLoadArraySfiidxLen = 8 * 112
269         typeInfoLoadArrayEtypesLen = 12
270         typeInfoLoadArrayBLen      = 8 * 4
271 )
272
273 type typeInfoLoad struct {
274         // fNames   []string
275         // encNames []string
276         etypes []uintptr
277         sfis   []structFieldInfo
278 }
279
280 type typeInfoLoadArray struct {
281         // fNames   [typeInfoLoadArrayLen]string
282         // encNames [typeInfoLoadArrayLen]string
283         sfis   [typeInfoLoadArraySfisLen]structFieldInfo
284         sfiidx [typeInfoLoadArraySfiidxLen]byte
285         etypes [typeInfoLoadArrayEtypesLen]uintptr
286         b      [typeInfoLoadArrayBLen]byte // scratch - used for struct field names
287 }
288
289 // mirror json.Marshaler and json.Unmarshaler here,
290 // so we don't import the encoding/json package
291
292 type jsonMarshaler interface {
293         MarshalJSON() ([]byte, error)
294 }
295 type jsonUnmarshaler interface {
296         UnmarshalJSON([]byte) error
297 }
298
299 type isZeroer interface {
300         IsZero() bool
301 }
302
303 type codecError struct {
304         name string
305         err  interface{}
306 }
307
308 func (e codecError) Cause() error {
309         switch xerr := e.err.(type) {
310         case nil:
311                 return nil
312         case error:
313                 return xerr
314         case string:
315                 return errors.New(xerr)
316         case fmt.Stringer:
317                 return errors.New(xerr.String())
318         default:
319                 return fmt.Errorf("%v", e.err)
320         }
321 }
322
323 func (e codecError) Error() string {
324         return fmt.Sprintf("%s error: %v", e.name, e.err)
325 }
326
327 // type byteAccepter func(byte) bool
328
329 var (
330         bigen               = binary.BigEndian
331         structInfoFieldName = "_struct"
332
333         mapStrIntfTyp  = reflect.TypeOf(map[string]interface{}(nil))
334         mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
335         intfSliceTyp   = reflect.TypeOf([]interface{}(nil))
336         intfTyp        = intfSliceTyp.Elem()
337
338         reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem()
339
340         stringTyp     = reflect.TypeOf("")
341         timeTyp       = reflect.TypeOf(time.Time{})
342         rawExtTyp     = reflect.TypeOf(RawExt{})
343         rawTyp        = reflect.TypeOf(Raw{})
344         uintptrTyp    = reflect.TypeOf(uintptr(0))
345         uint8Typ      = reflect.TypeOf(uint8(0))
346         uint8SliceTyp = reflect.TypeOf([]uint8(nil))
347         uintTyp       = reflect.TypeOf(uint(0))
348         intTyp        = reflect.TypeOf(int(0))
349
350         mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
351
352         binaryMarshalerTyp   = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
353         binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
354
355         textMarshalerTyp   = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
356         textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
357
358         jsonMarshalerTyp   = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
359         jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
360
361         selferTyp         = reflect.TypeOf((*Selfer)(nil)).Elem()
362         missingFielderTyp = reflect.TypeOf((*MissingFielder)(nil)).Elem()
363         iszeroTyp         = reflect.TypeOf((*isZeroer)(nil)).Elem()
364
365         uint8TypId      = rt2id(uint8Typ)
366         uint8SliceTypId = rt2id(uint8SliceTyp)
367         rawExtTypId     = rt2id(rawExtTyp)
368         rawTypId        = rt2id(rawTyp)
369         intfTypId       = rt2id(intfTyp)
370         timeTypId       = rt2id(timeTyp)
371         stringTypId     = rt2id(stringTyp)
372
373         mapStrIntfTypId  = rt2id(mapStrIntfTyp)
374         mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
375         intfSliceTypId   = rt2id(intfSliceTyp)
376         // mapBySliceTypId  = rt2id(mapBySliceTyp)
377
378         intBitsize  = uint8(intTyp.Bits())
379         uintBitsize = uint8(uintTyp.Bits())
380
381         bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
382         bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
383
384         chkOvf checkOverflow
385
386         errNoFieldNameToStructFieldInfo = errors.New("no field name passed to parseStructFieldInfo")
387 )
388
389 var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
390
391 var immutableKindsSet = [32]bool{
392         // reflect.Invalid:  ,
393         reflect.Bool:       true,
394         reflect.Int:        true,
395         reflect.Int8:       true,
396         reflect.Int16:      true,
397         reflect.Int32:      true,
398         reflect.Int64:      true,
399         reflect.Uint:       true,
400         reflect.Uint8:      true,
401         reflect.Uint16:     true,
402         reflect.Uint32:     true,
403         reflect.Uint64:     true,
404         reflect.Uintptr:    true,
405         reflect.Float32:    true,
406         reflect.Float64:    true,
407         reflect.Complex64:  true,
408         reflect.Complex128: true,
409         // reflect.Array
410         // reflect.Chan
411         // reflect.Func: true,
412         // reflect.Interface
413         // reflect.Map
414         // reflect.Ptr
415         // reflect.Slice
416         reflect.String: true,
417         // reflect.Struct
418         // reflect.UnsafePointer
419 }
420
421 // Selfer defines methods by which a value can encode or decode itself.
422 //
423 // Any type which implements Selfer will be able to encode or decode itself.
424 // Consequently, during (en|de)code, this takes precedence over
425 // (text|binary)(M|Unm)arshal or extension support.
426 //
427 // Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
428 // This is because, during each decode, we first check the the next set of bytes
429 // represent nil, and if so, we just set the value to nil.
430 type Selfer interface {
431         CodecEncodeSelf(*Encoder)
432         CodecDecodeSelf(*Decoder)
433 }
434
435 // MissingFielder defines the interface allowing structs to internally decode or encode
436 // values which do not map to struct fields.
437 //
438 // We expect that this interface is bound to a pointer type (so the mutation function works).
439 //
440 // A use-case is if a version of a type unexports a field, but you want compatibility between
441 // both versions during encoding and decoding.
442 //
443 // Note that the interface is completely ignored during codecgen.
444 type MissingFielder interface {
445         // CodecMissingField is called to set a missing field and value pair.
446         //
447         // It returns true if the missing field was set on the struct.
448         CodecMissingField(field []byte, value interface{}) bool
449
450         // CodecMissingFields returns the set of fields which are not struct fields
451         CodecMissingFields() map[string]interface{}
452 }
453
454 // MapBySlice is a tag interface that denotes wrapped slice should encode as a map in the stream.
455 // The slice contains a sequence of key-value pairs.
456 // This affords storing a map in a specific sequence in the stream.
457 //
458 // Example usage:
459 //    type T1 []string         // or []int or []Point or any other "slice" type
460 //    func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map
461 //    type T2 struct { KeyValues T1 }
462 //
463 //    var kvs = []string{"one", "1", "two", "2", "three", "3"}
464 //    var v2 = T2{ KeyValues: T1(kvs) }
465 //    // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} }
466 //
467 // The support of MapBySlice affords the following:
468 //   - A slice type which implements MapBySlice will be encoded as a map
469 //   - A slice can be decoded from a map in the stream
470 //   - It MUST be a slice type (not a pointer receiver) that implements MapBySlice
471 type MapBySlice interface {
472         MapBySlice()
473 }
474
475 // BasicHandle encapsulates the common options and extension functions.
476 //
477 // Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
478 type BasicHandle struct {
479         // BasicHandle is always a part of a different type.
480         // It doesn't have to fit into it own cache lines.
481
482         // TypeInfos is used to get the type info for any type.
483         //
484         // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
485         TypeInfos *TypeInfos
486
487         // Note: BasicHandle is not comparable, due to these slices here (extHandle, intf2impls).
488         // If *[]T is used instead, this becomes comparable, at the cost of extra indirection.
489         // Thses slices are used all the time, so keep as slices (not pointers).
490
491         extHandle
492
493         intf2impls
494
495         RPCOptions
496
497         // TimeNotBuiltin configures whether time.Time should be treated as a builtin type.
498         //
499         // All Handlers should know how to encode/decode time.Time as part of the core
500         // format specification, or as a standard extension defined by the format.
501         //
502         // However, users can elect to handle time.Time as a custom extension, or via the
503         // standard library's encoding.Binary(M|Unm)arshaler or Text(M|Unm)arshaler interface.
504         // To elect this behavior, users can set TimeNotBuiltin=true.
505         // Note: Setting TimeNotBuiltin=true can be used to enable the legacy behavior
506         // (for Cbor and Msgpack), where time.Time was not a builtin supported type.
507         TimeNotBuiltin bool
508
509         // ---- cache line
510
511         DecodeOptions
512
513         // ---- cache line
514
515         EncodeOptions
516
517         // noBuiltInTypeChecker
518 }
519
520 func (x *BasicHandle) getBasicHandle() *BasicHandle {
521         return x
522 }
523
524 func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
525         if x.TypeInfos == nil {
526                 return defTypeInfos.get(rtid, rt)
527         }
528         return x.TypeInfos.get(rtid, rt)
529 }
530
531 // Handle is the interface for a specific encoding format.
532 //
533 // Typically, a Handle is pre-configured before first time use,
534 // and not modified while in use. Such a pre-configured Handle
535 // is safe for concurrent access.
536 type Handle interface {
537         Name() string
538         getBasicHandle() *BasicHandle
539         recreateEncDriver(encDriver) bool
540         newEncDriver(w *Encoder) encDriver
541         newDecDriver(r *Decoder) decDriver
542         isBinary() bool
543         hasElemSeparators() bool
544         // IsBuiltinType(rtid uintptr) bool
545 }
546
547 // Raw represents raw formatted bytes.
548 // We "blindly" store it during encode and retrieve the raw bytes during decode.
549 // Note: it is dangerous during encode, so we may gate the behaviour
550 // behind an Encode flag which must be explicitly set.
551 type Raw []byte
552
553 // RawExt represents raw unprocessed extension data.
554 // Some codecs will decode extension data as a *RawExt
555 // if there is no registered extension for the tag.
556 //
557 // Only one of Data or Value is nil.
558 // If Data is nil, then the content of the RawExt is in the Value.
559 type RawExt struct {
560         Tag uint64
561         // Data is the []byte which represents the raw ext. If nil, ext is exposed in Value.
562         // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types
563         Data []byte
564         // Value represents the extension, if Data is nil.
565         // Value is used by codecs (e.g. cbor, json) which leverage the format to do
566         // custom serialization of the types.
567         Value interface{}
568 }
569
570 // BytesExt handles custom (de)serialization of types to/from []byte.
571 // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
572 type BytesExt interface {
573         // WriteExt converts a value to a []byte.
574         //
575         // Note: v is a pointer iff the registered extension type is a struct or array kind.
576         WriteExt(v interface{}) []byte
577
578         // ReadExt updates a value from a []byte.
579         //
580         // Note: dst is always a pointer kind to the registered extension type.
581         ReadExt(dst interface{}, src []byte)
582 }
583
584 // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
585 // The Encoder or Decoder will then handle the further (de)serialization of that known type.
586 //
587 // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types.
588 type InterfaceExt interface {
589         // ConvertExt converts a value into a simpler interface for easy encoding
590         // e.g. convert time.Time to int64.
591         //
592         // Note: v is a pointer iff the registered extension type is a struct or array kind.
593         ConvertExt(v interface{}) interface{}
594
595         // UpdateExt updates a value from a simpler interface for easy decoding
596         // e.g. convert int64 to time.Time.
597         //
598         // Note: dst is always a pointer kind to the registered extension type.
599         UpdateExt(dst interface{}, src interface{})
600 }
601
602 // Ext handles custom (de)serialization of custom types / extensions.
603 type Ext interface {
604         BytesExt
605         InterfaceExt
606 }
607
608 // addExtWrapper is a wrapper implementation to support former AddExt exported method.
609 type addExtWrapper struct {
610         encFn func(reflect.Value) ([]byte, error)
611         decFn func(reflect.Value, []byte) error
612 }
613
614 func (x addExtWrapper) WriteExt(v interface{}) []byte {
615         bs, err := x.encFn(reflect.ValueOf(v))
616         if err != nil {
617                 panic(err)
618         }
619         return bs
620 }
621
622 func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
623         if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
624                 panic(err)
625         }
626 }
627
628 func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
629         return x.WriteExt(v)
630 }
631
632 func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
633         x.ReadExt(dest, v.([]byte))
634 }
635
636 type extWrapper struct {
637         BytesExt
638         InterfaceExt
639 }
640
641 type bytesExtFailer struct{}
642
643 func (bytesExtFailer) WriteExt(v interface{}) []byte {
644         panicv.errorstr("BytesExt.WriteExt is not supported")
645         return nil
646 }
647 func (bytesExtFailer) ReadExt(v interface{}, bs []byte) {
648         panicv.errorstr("BytesExt.ReadExt is not supported")
649 }
650
651 type interfaceExtFailer struct{}
652
653 func (interfaceExtFailer) ConvertExt(v interface{}) interface{} {
654         panicv.errorstr("InterfaceExt.ConvertExt is not supported")
655         return nil
656 }
657 func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) {
658         panicv.errorstr("InterfaceExt.UpdateExt is not supported")
659 }
660
661 type binaryEncodingType struct{}
662
663 func (binaryEncodingType) isBinary() bool { return true }
664
665 type textEncodingType struct{}
666
667 func (textEncodingType) isBinary() bool { return false }
668
669 // noBuiltInTypes is embedded into many types which do not support builtins
670 // e.g. msgpack, simple, cbor.
671
672 // type noBuiltInTypeChecker struct{}
673 // func (noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
674 // type noBuiltInTypes struct{ noBuiltInTypeChecker }
675
676 type noBuiltInTypes struct{}
677
678 func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
679 func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
680
681 // type noStreamingCodec struct{}
682 // func (noStreamingCodec) CheckBreak() bool { return false }
683 // func (noStreamingCodec) hasElemSeparators() bool { return false }
684
685 type noElemSeparators struct{}
686
687 func (noElemSeparators) hasElemSeparators() (v bool)            { return }
688 func (noElemSeparators) recreateEncDriver(e encDriver) (v bool) { return }
689
690 // bigenHelper.
691 // Users must already slice the x completely, because we will not reslice.
692 type bigenHelper struct {
693         x []byte // must be correctly sliced to appropriate len. slicing is a cost.
694         w encWriter
695 }
696
697 func (z bigenHelper) writeUint16(v uint16) {
698         bigen.PutUint16(z.x, v)
699         z.w.writeb(z.x)
700 }
701
702 func (z bigenHelper) writeUint32(v uint32) {
703         bigen.PutUint32(z.x, v)
704         z.w.writeb(z.x)
705 }
706
707 func (z bigenHelper) writeUint64(v uint64) {
708         bigen.PutUint64(z.x, v)
709         z.w.writeb(z.x)
710 }
711
712 type extTypeTagFn struct {
713         rtid    uintptr
714         rtidptr uintptr
715         rt      reflect.Type
716         tag     uint64
717         ext     Ext
718         _       [1]uint64 // padding
719 }
720
721 type extHandle []extTypeTagFn
722
723 // AddExt registes an encode and decode function for a reflect.Type.
724 // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
725 //
726 // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
727 func (o *extHandle) AddExt(rt reflect.Type, tag byte,
728         encfn func(reflect.Value) ([]byte, error),
729         decfn func(reflect.Value, []byte) error) (err error) {
730         if encfn == nil || decfn == nil {
731                 return o.SetExt(rt, uint64(tag), nil)
732         }
733         return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
734 }
735
736 // SetExt will set the extension for a tag and reflect.Type.
737 // Note that the type must be a named type, and specifically not a pointer or Interface.
738 // An error is returned if that is not honored.
739 // To Deregister an ext, call SetExt with nil Ext.
740 //
741 // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
742 func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
743         // o is a pointer, because we may need to initialize it
744         rk := rt.Kind()
745         for rk == reflect.Ptr {
746                 rt = rt.Elem()
747                 rk = rt.Kind()
748         }
749
750         if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr {
751                 return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt)
752         }
753
754         rtid := rt2id(rt)
755         switch rtid {
756         case timeTypId, rawTypId, rawExtTypId:
757                 // all natively supported type, so cannot have an extension
758                 return // TODO: should we silently ignore, or return an error???
759         }
760         // if o == nil {
761         //      return errors.New("codec.Handle.SetExt: extHandle not initialized")
762         // }
763         o2 := *o
764         // if o2 == nil {
765         //      return errors.New("codec.Handle.SetExt: extHandle not initialized")
766         // }
767         for i := range o2 {
768                 v := &o2[i]
769                 if v.rtid == rtid {
770                         v.tag, v.ext = tag, ext
771                         return
772                 }
773         }
774         rtidptr := rt2id(reflect.PtrTo(rt))
775         *o = append(o2, extTypeTagFn{rtid, rtidptr, rt, tag, ext, [1]uint64{}})
776         return
777 }
778
779 func (o extHandle) getExt(rtid uintptr) (v *extTypeTagFn) {
780         for i := range o {
781                 v = &o[i]
782                 if v.rtid == rtid || v.rtidptr == rtid {
783                         return
784                 }
785         }
786         return nil
787 }
788
789 func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) {
790         for i := range o {
791                 v = &o[i]
792                 if v.tag == tag {
793                         return
794                 }
795         }
796         return nil
797 }
798
799 type intf2impl struct {
800         rtid uintptr // for intf
801         impl reflect.Type
802         // _    [1]uint64 // padding // not-needed, as *intf2impl is never returned.
803 }
804
805 type intf2impls []intf2impl
806
807 // Intf2Impl maps an interface to an implementing type.
808 // This allows us support infering the concrete type
809 // and populating it when passed an interface.
810 // e.g. var v io.Reader can be decoded as a bytes.Buffer, etc.
811 //
812 // Passing a nil impl will clear the mapping.
813 func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) {
814         if impl != nil && !impl.Implements(intf) {
815                 return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf)
816         }
817         rtid := rt2id(intf)
818         o2 := *o
819         for i := range o2 {
820                 v := &o2[i]
821                 if v.rtid == rtid {
822                         v.impl = impl
823                         return
824                 }
825         }
826         *o = append(o2, intf2impl{rtid, impl})
827         return
828 }
829
830 func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) {
831         for i := range o {
832                 v := &o[i]
833                 if v.rtid == rtid {
834                         if v.impl == nil {
835                                 return
836                         }
837                         if v.impl.Kind() == reflect.Ptr {
838                                 return reflect.New(v.impl.Elem())
839                         }
840                         return reflect.New(v.impl).Elem()
841                 }
842         }
843         return
844 }
845
846 type structFieldInfoFlag uint8
847
848 const (
849         _ structFieldInfoFlag = 1 << iota
850         structFieldInfoFlagReady
851         structFieldInfoFlagOmitEmpty
852 )
853
854 func (x *structFieldInfoFlag) flagSet(f structFieldInfoFlag) {
855         *x = *x | f
856 }
857
858 func (x *structFieldInfoFlag) flagClr(f structFieldInfoFlag) {
859         *x = *x &^ f
860 }
861
862 func (x structFieldInfoFlag) flagGet(f structFieldInfoFlag) bool {
863         return x&f != 0
864 }
865
866 func (x structFieldInfoFlag) omitEmpty() bool {
867         return x.flagGet(structFieldInfoFlagOmitEmpty)
868 }
869
870 func (x structFieldInfoFlag) ready() bool {
871         return x.flagGet(structFieldInfoFlagReady)
872 }
873
874 type structFieldInfo struct {
875         encName   string // encode name
876         fieldName string // field name
877
878         is  [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
879         nis uint8                      // num levels of embedding. if 1, then it's not embedded.
880
881         encNameAsciiAlphaNum bool // the encName only contains ascii alphabet and numbers
882         structFieldInfoFlag
883         _ [1]byte // padding
884 }
885
886 func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
887         if v, valid := si.field(v, false); valid {
888                 v.Set(reflect.Zero(v.Type()))
889         }
890 }
891
892 // rv returns the field of the struct.
893 // If anonymous, it returns an Invalid
894 func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
895         // replicate FieldByIndex
896         for i, x := range si.is {
897                 if uint8(i) == si.nis {
898                         break
899                 }
900                 if v, valid = baseStructRv(v, update); !valid {
901                         return
902                 }
903                 v = v.Field(int(x))
904         }
905
906         return v, true
907 }
908
909 // func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
910 //      v, _ = si.field(v, update)
911 //      return v
912 // }
913
914 func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) {
915         keytype = valueTypeString // default
916         if stag == "" {
917                 return
918         }
919         for i, s := range strings.Split(stag, ",") {
920                 if i == 0 {
921                 } else {
922                         switch s {
923                         case "omitempty":
924                                 omitEmpty = true
925                         case "toarray":
926                                 toArray = true
927                         case "int":
928                                 keytype = valueTypeInt
929                         case "uint":
930                                 keytype = valueTypeUint
931                         case "float":
932                                 keytype = valueTypeFloat
933                                 // case "bool":
934                                 //      keytype = valueTypeBool
935                         case "string":
936                                 keytype = valueTypeString
937                         }
938                 }
939         }
940         return
941 }
942
943 func (si *structFieldInfo) parseTag(stag string) {
944         // if fname == "" {
945         //      panic(errNoFieldNameToStructFieldInfo)
946         // }
947
948         if stag == "" {
949                 return
950         }
951         for i, s := range strings.Split(stag, ",") {
952                 if i == 0 {
953                         if s != "" {
954                                 si.encName = s
955                         }
956                 } else {
957                         switch s {
958                         case "omitempty":
959                                 si.flagSet(structFieldInfoFlagOmitEmpty)
960                                 // si.omitEmpty = true
961                                 // case "toarray":
962                                 //      si.toArray = true
963                         }
964                 }
965         }
966 }
967
968 type sfiSortedByEncName []*structFieldInfo
969
970 func (p sfiSortedByEncName) Len() int {
971         return len(p)
972 }
973
974 func (p sfiSortedByEncName) Less(i, j int) bool {
975         return p[i].encName < p[j].encName
976 }
977
978 func (p sfiSortedByEncName) Swap(i, j int) {
979         p[i], p[j] = p[j], p[i]
980 }
981
982 const structFieldNodeNumToCache = 4
983
984 type structFieldNodeCache struct {
985         rv  [structFieldNodeNumToCache]reflect.Value
986         idx [structFieldNodeNumToCache]uint32
987         num uint8
988 }
989
990 func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
991         for i, k := range &x.idx {
992                 if uint8(i) == x.num {
993                         return // break
994                 }
995                 if key == k {
996                         return x.rv[i], true
997                 }
998         }
999         return
1000 }
1001
1002 func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
1003         if x.num < structFieldNodeNumToCache {
1004                 x.rv[x.num] = fv
1005                 x.idx[x.num] = key
1006                 x.num++
1007                 return
1008         }
1009 }
1010
1011 type structFieldNode struct {
1012         v      reflect.Value
1013         cache2 structFieldNodeCache
1014         cache3 structFieldNodeCache
1015         update bool
1016 }
1017
1018 func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
1019         // return si.fieldval(x.v, x.update)
1020         // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
1021         // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
1022         var valid bool
1023         switch si.nis {
1024         case 1:
1025                 fv = x.v.Field(int(si.is[0]))
1026         case 2:
1027                 if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
1028                         fv = fv.Field(int(si.is[1]))
1029                         return
1030                 }
1031                 fv = x.v.Field(int(si.is[0]))
1032                 if fv, valid = baseStructRv(fv, x.update); !valid {
1033                         return
1034                 }
1035                 x.cache2.tryAdd(fv, uint32(si.is[0]))
1036                 fv = fv.Field(int(si.is[1]))
1037         case 3:
1038                 var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
1039                 if fv, valid = x.cache3.get(key); valid {
1040                         fv = fv.Field(int(si.is[2]))
1041                         return
1042                 }
1043                 fv = x.v.Field(int(si.is[0]))
1044                 if fv, valid = baseStructRv(fv, x.update); !valid {
1045                         return
1046                 }
1047                 fv = fv.Field(int(si.is[1]))
1048                 if fv, valid = baseStructRv(fv, x.update); !valid {
1049                         return
1050                 }
1051                 x.cache3.tryAdd(fv, key)
1052                 fv = fv.Field(int(si.is[2]))
1053         default:
1054                 fv, _ = si.field(x.v, x.update)
1055         }
1056         return
1057 }
1058
1059 func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
1060         for v.Kind() == reflect.Ptr {
1061                 if v.IsNil() {
1062                         if !update {
1063                                 return
1064                         }
1065                         v.Set(reflect.New(v.Type().Elem()))
1066                 }
1067                 v = v.Elem()
1068         }
1069         return v, true
1070 }
1071
1072 type typeInfoFlag uint8
1073
1074 const (
1075         typeInfoFlagComparable = 1 << iota
1076         typeInfoFlagIsZeroer
1077         typeInfoFlagIsZeroerPtr
1078 )
1079
1080 // typeInfo keeps information about each (non-ptr) type referenced in the encode/decode sequence.
1081 //
1082 // During an encode/decode sequence, we work as below:
1083 //   - If base is a built in type, en/decode base value
1084 //   - If base is registered as an extension, en/decode base value
1085 //   - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
1086 //   - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
1087 //   - Else decode appropriately based on the reflect.Kind
1088 type typeInfo struct {
1089         rt      reflect.Type
1090         elem    reflect.Type
1091         pkgpath string
1092
1093         rtid uintptr
1094         // rv0  reflect.Value // saved zero value, used if immutableKind
1095
1096         numMeth uint16 // number of methods
1097         kind    uint8
1098         chandir uint8
1099
1100         anyOmitEmpty bool      // true if a struct, and any of the fields are tagged "omitempty"
1101         toArray      bool      // whether this (struct) type should be encoded as an array
1102         keyType      valueType // if struct, how is the field name stored in a stream? default is string
1103         mbs          bool      // base type (T or *T) is a MapBySlice
1104
1105         // ---- cpu cache line boundary?
1106         sfiSort []*structFieldInfo // sorted. Used when enc/dec struct to map.
1107         sfiSrc  []*structFieldInfo // unsorted. Used when enc/dec struct to array.
1108
1109         key reflect.Type
1110
1111         // ---- cpu cache line boundary?
1112         // sfis         []structFieldInfo // all sfi, in src order, as created.
1113         sfiNamesSort []byte // all names, with indexes into the sfiSort
1114
1115         // format of marshal type fields below: [btj][mu]p? OR csp?
1116
1117         bm  bool // T is a binaryMarshaler
1118         bmp bool // *T is a binaryMarshaler
1119         bu  bool // T is a binaryUnmarshaler
1120         bup bool // *T is a binaryUnmarshaler
1121         tm  bool // T is a textMarshaler
1122         tmp bool // *T is a textMarshaler
1123         tu  bool // T is a textUnmarshaler
1124         tup bool // *T is a textUnmarshaler
1125
1126         jm  bool // T is a jsonMarshaler
1127         jmp bool // *T is a jsonMarshaler
1128         ju  bool // T is a jsonUnmarshaler
1129         jup bool // *T is a jsonUnmarshaler
1130         cs  bool // T is a Selfer
1131         csp bool // *T is a Selfer
1132         mf  bool // T is a MissingFielder
1133         mfp bool // *T is a MissingFielder
1134
1135         // other flags, with individual bits representing if set.
1136         flags              typeInfoFlag
1137         infoFieldOmitempty bool
1138
1139         _ [6]byte   // padding
1140         _ [2]uint64 // padding
1141 }
1142
1143 func (ti *typeInfo) isFlag(f typeInfoFlag) bool {
1144         return ti.flags&f != 0
1145 }
1146
1147 func (ti *typeInfo) indexForEncName(name []byte) (index int16) {
1148         var sn []byte
1149         if len(name)+2 <= 32 {
1150                 var buf [32]byte // should not escape
1151                 sn = buf[:len(name)+2]
1152         } else {
1153                 sn = make([]byte, len(name)+2)
1154         }
1155         copy(sn[1:], name)
1156         sn[0], sn[len(sn)-1] = tiSep2(name), 0xff
1157         j := bytes.Index(ti.sfiNamesSort, sn)
1158         if j < 0 {
1159                 return -1
1160         }
1161         index = int16(uint16(ti.sfiNamesSort[j+len(sn)+1]) | uint16(ti.sfiNamesSort[j+len(sn)])<<8)
1162         return
1163 }
1164
1165 type rtid2ti struct {
1166         rtid uintptr
1167         ti   *typeInfo
1168 }
1169
1170 // TypeInfos caches typeInfo for each type on first inspection.
1171 //
1172 // It is configured with a set of tag keys, which are used to get
1173 // configuration for the type.
1174 type TypeInfos struct {
1175         // infos: formerly map[uintptr]*typeInfo, now *[]rtid2ti, 2 words expected
1176         infos atomicTypeInfoSlice
1177         mu    sync.Mutex
1178         tags  []string
1179         _     [2]uint64 // padding
1180 }
1181
1182 // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
1183 //
1184 // This allows users customize the struct tag keys which contain configuration
1185 // of their types.
1186 func NewTypeInfos(tags []string) *TypeInfos {
1187         return &TypeInfos{tags: tags}
1188 }
1189
1190 func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
1191         // check for tags: codec, json, in that order.
1192         // this allows seamless support for many configured structs.
1193         for _, x := range x.tags {
1194                 s = t.Get(x)
1195                 if s != "" {
1196                         return s
1197                 }
1198         }
1199         return
1200 }
1201
1202 func (x *TypeInfos) find(s []rtid2ti, rtid uintptr) (idx int, ti *typeInfo) {
1203         // binary search. adapted from sort/search.go.
1204         // if sp == nil {
1205         //      return -1, nil
1206         // }
1207         // s := *sp
1208         h, i, j := 0, 0, len(s)
1209         for i < j {
1210                 h = i + (j-i)/2
1211                 if s[h].rtid < rtid {
1212                         i = h + 1
1213                 } else {
1214                         j = h
1215                 }
1216         }
1217         if i < len(s) && s[i].rtid == rtid {
1218                 return i, s[i].ti
1219         }
1220         return i, nil
1221 }
1222
1223 func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
1224         sp := x.infos.load()
1225         var idx int
1226         if sp != nil {
1227                 idx, pti = x.find(sp, rtid)
1228                 if pti != nil {
1229                         return
1230                 }
1231         }
1232
1233         rk := rt.Kind()
1234
1235         if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) {
1236                 panicv.errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt)
1237         }
1238
1239         // do not hold lock while computing this.
1240         // it may lead to duplication, but that's ok.
1241         ti := typeInfo{
1242                 rt:      rt,
1243                 rtid:    rtid,
1244                 kind:    uint8(rk),
1245                 pkgpath: rt.PkgPath(),
1246                 keyType: valueTypeString, // default it - so it's never 0
1247         }
1248         // ti.rv0 = reflect.Zero(rt)
1249
1250         // ti.comparable = rt.Comparable()
1251         ti.numMeth = uint16(rt.NumMethod())
1252
1253         ti.bm, ti.bmp = implIntf(rt, binaryMarshalerTyp)
1254         ti.bu, ti.bup = implIntf(rt, binaryUnmarshalerTyp)
1255         ti.tm, ti.tmp = implIntf(rt, textMarshalerTyp)
1256         ti.tu, ti.tup = implIntf(rt, textUnmarshalerTyp)
1257         ti.jm, ti.jmp = implIntf(rt, jsonMarshalerTyp)
1258         ti.ju, ti.jup = implIntf(rt, jsonUnmarshalerTyp)
1259         ti.cs, ti.csp = implIntf(rt, selferTyp)
1260         ti.mf, ti.mfp = implIntf(rt, missingFielderTyp)
1261
1262         b1, b2 := implIntf(rt, iszeroTyp)
1263         if b1 {
1264                 ti.flags |= typeInfoFlagIsZeroer
1265         }
1266         if b2 {
1267                 ti.flags |= typeInfoFlagIsZeroerPtr
1268         }
1269         if rt.Comparable() {
1270                 ti.flags |= typeInfoFlagComparable
1271         }
1272
1273         switch rk {
1274         case reflect.Struct:
1275                 var omitEmpty bool
1276                 if f, ok := rt.FieldByName(structInfoFieldName); ok {
1277                         ti.toArray, omitEmpty, ti.keyType = parseStructInfo(x.structTag(f.Tag))
1278                         ti.infoFieldOmitempty = omitEmpty
1279                 } else {
1280                         ti.keyType = valueTypeString
1281                 }
1282                 pp, pi := pool.tiLoad()
1283                 pv := pi.(*typeInfoLoadArray)
1284                 pv.etypes[0] = ti.rtid
1285                 // vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
1286                 vv := typeInfoLoad{pv.etypes[:1], pv.sfis[:0]}
1287                 x.rget(rt, rtid, omitEmpty, nil, &vv)
1288                 // ti.sfis = vv.sfis
1289                 ti.sfiSrc, ti.sfiSort, ti.sfiNamesSort, ti.anyOmitEmpty = rgetResolveSFI(rt, vv.sfis, pv)
1290                 pp.Put(pi)
1291         case reflect.Map:
1292                 ti.elem = rt.Elem()
1293                 ti.key = rt.Key()
1294         case reflect.Slice:
1295                 ti.mbs, _ = implIntf(rt, mapBySliceTyp)
1296                 ti.elem = rt.Elem()
1297         case reflect.Chan:
1298                 ti.elem = rt.Elem()
1299                 ti.chandir = uint8(rt.ChanDir())
1300         case reflect.Array, reflect.Ptr:
1301                 ti.elem = rt.Elem()
1302         }
1303         // sfi = sfiSrc
1304
1305         x.mu.Lock()
1306         sp = x.infos.load()
1307         if sp == nil {
1308                 pti = &ti
1309                 vs := []rtid2ti{{rtid, pti}}
1310                 x.infos.store(vs)
1311         } else {
1312                 idx, pti = x.find(sp, rtid)
1313                 if pti == nil {
1314                         pti = &ti
1315                         vs := make([]rtid2ti, len(sp)+1)
1316                         copy(vs, sp[:idx])
1317                         copy(vs[idx+1:], sp[idx:])
1318                         vs[idx] = rtid2ti{rtid, pti}
1319                         x.infos.store(vs)
1320                 }
1321         }
1322         x.mu.Unlock()
1323         return
1324 }
1325
1326 func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
1327         indexstack []uint16, pv *typeInfoLoad) {
1328         // Read up fields and store how to access the value.
1329         //
1330         // It uses go's rules for message selectors,
1331         // which say that the field with the shallowest depth is selected.
1332         //
1333         // Note: we consciously use slices, not a map, to simulate a set.
1334         //       Typically, types have < 16 fields,
1335         //       and iteration using equals is faster than maps there
1336         flen := rt.NumField()
1337         if flen > (1<<maxLevelsEmbedding - 1) {
1338                 panicv.errorf("codec: types with > %v fields are not supported - has %v fields",
1339                         (1<<maxLevelsEmbedding - 1), flen)
1340         }
1341         // pv.sfis = make([]structFieldInfo, flen)
1342 LOOP:
1343         for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
1344                 f := rt.Field(int(j))
1345                 fkind := f.Type.Kind()
1346                 // skip if a func type, or is unexported, or structTag value == "-"
1347                 switch fkind {
1348                 case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
1349                         continue LOOP
1350                 }
1351
1352                 isUnexported := f.PkgPath != ""
1353                 if isUnexported && !f.Anonymous {
1354                         continue
1355                 }
1356                 stag := x.structTag(f.Tag)
1357                 if stag == "-" {
1358                         continue
1359                 }
1360                 var si structFieldInfo
1361                 var parsed bool
1362                 // if anonymous and no struct tag (or it's blank),
1363                 // and a struct (or pointer to struct), inline it.
1364                 if f.Anonymous && fkind != reflect.Interface {
1365                         // ^^ redundant but ok: per go spec, an embedded pointer type cannot be to an interface
1366                         ft := f.Type
1367                         isPtr := ft.Kind() == reflect.Ptr
1368                         for ft.Kind() == reflect.Ptr {
1369                                 ft = ft.Elem()
1370                         }
1371                         isStruct := ft.Kind() == reflect.Struct
1372
1373                         // Ignore embedded fields of unexported non-struct types.
1374                         // Also, from go1.10, ignore pointers to unexported struct types
1375                         // because unmarshal cannot assign a new struct to an unexported field.
1376                         // See https://golang.org/issue/21357
1377                         if (isUnexported && !isStruct) || (!allowSetUnexportedEmbeddedPtr && isUnexported && isPtr) {
1378                                 continue
1379                         }
1380                         doInline := stag == ""
1381                         if !doInline {
1382                                 si.parseTag(stag)
1383                                 parsed = true
1384                                 doInline = si.encName == ""
1385                                 // doInline = si.isZero()
1386                         }
1387                         if doInline && isStruct {
1388                                 // if etypes contains this, don't call rget again (as fields are already seen here)
1389                                 ftid := rt2id(ft)
1390                                 // We cannot recurse forever, but we need to track other field depths.
1391                                 // So - we break if we see a type twice (not the first time).
1392                                 // This should be sufficient to handle an embedded type that refers to its
1393                                 // owning type, which then refers to its embedded type.
1394                                 processIt := true
1395                                 numk := 0
1396                                 for _, k := range pv.etypes {
1397                                         if k == ftid {
1398                                                 numk++
1399                                                 if numk == rgetMaxRecursion {
1400                                                         processIt = false
1401                                                         break
1402                                                 }
1403                                         }
1404                                 }
1405                                 if processIt {
1406                                         pv.etypes = append(pv.etypes, ftid)
1407                                         indexstack2 := make([]uint16, len(indexstack)+1)
1408                                         copy(indexstack2, indexstack)
1409                                         indexstack2[len(indexstack)] = j
1410                                         // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
1411                                         x.rget(ft, ftid, omitEmpty, indexstack2, pv)
1412                                 }
1413                                 continue
1414                         }
1415                 }
1416
1417                 // after the anonymous dance: if an unexported field, skip
1418                 if isUnexported {
1419                         continue
1420                 }
1421
1422                 if f.Name == "" {
1423                         panic(errNoFieldNameToStructFieldInfo)
1424                 }
1425
1426                 // pv.fNames = append(pv.fNames, f.Name)
1427                 // if si.encName == "" {
1428
1429                 if !parsed {
1430                         si.encName = f.Name
1431                         si.parseTag(stag)
1432                         parsed = true
1433                 } else if si.encName == "" {
1434                         si.encName = f.Name
1435                 }
1436                 si.encNameAsciiAlphaNum = true
1437                 for i := len(si.encName) - 1; i >= 0; i-- {
1438                         b := si.encName[i]
1439                         if (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') {
1440                                 continue
1441                         }
1442                         si.encNameAsciiAlphaNum = false
1443                         break
1444                 }
1445                 si.fieldName = f.Name
1446                 si.flagSet(structFieldInfoFlagReady)
1447
1448                 // pv.encNames = append(pv.encNames, si.encName)
1449
1450                 // si.ikind = int(f.Type.Kind())
1451                 if len(indexstack) > maxLevelsEmbedding-1 {
1452                         panicv.errorf("codec: only supports up to %v depth of embedding - type has %v depth",
1453                                 maxLevelsEmbedding-1, len(indexstack))
1454                 }
1455                 si.nis = uint8(len(indexstack)) + 1
1456                 copy(si.is[:], indexstack)
1457                 si.is[len(indexstack)] = j
1458
1459                 if omitEmpty {
1460                         si.flagSet(structFieldInfoFlagOmitEmpty)
1461                 }
1462                 pv.sfis = append(pv.sfis, si)
1463         }
1464 }
1465
1466 func tiSep(name string) uint8 {
1467         // (xn[0]%64) // (between 192-255 - outside ascii BMP)
1468         // return 0xfe - (name[0] & 63)
1469         // return 0xfe - (name[0] & 63) - uint8(len(name))
1470         // return 0xfe - (name[0] & 63) - uint8(len(name)&63)
1471         // return ((0xfe - (name[0] & 63)) & 0xf8) | (uint8(len(name) & 0x07))
1472         return 0xfe - (name[0] & 63) - uint8(len(name)&63)
1473 }
1474
1475 func tiSep2(name []byte) uint8 {
1476         return 0xfe - (name[0] & 63) - uint8(len(name)&63)
1477 }
1478
1479 // resolves the struct field info got from a call to rget.
1480 // Returns a trimmed, unsorted and sorted []*structFieldInfo.
1481 func rgetResolveSFI(rt reflect.Type, x []structFieldInfo, pv *typeInfoLoadArray) (
1482         y, z []*structFieldInfo, ss []byte, anyOmitEmpty bool) {
1483         sa := pv.sfiidx[:0]
1484         sn := pv.b[:]
1485         n := len(x)
1486
1487         var xn string
1488         var ui uint16
1489         var sep byte
1490
1491         for i := range x {
1492                 ui = uint16(i)
1493                 xn = x[i].encName // fieldName or encName? use encName for now.
1494                 if len(xn)+2 > cap(pv.b) {
1495                         sn = make([]byte, len(xn)+2)
1496                 } else {
1497                         sn = sn[:len(xn)+2]
1498                 }
1499                 // use a custom sep, so that misses are less frequent,
1500                 // since the sep (first char in search) is as unique as first char in field name.
1501                 sep = tiSep(xn)
1502                 sn[0], sn[len(sn)-1] = sep, 0xff
1503                 copy(sn[1:], xn)
1504                 j := bytes.Index(sa, sn)
1505                 if j == -1 {
1506                         sa = append(sa, sep)
1507                         sa = append(sa, xn...)
1508                         sa = append(sa, 0xff, byte(ui>>8), byte(ui))
1509                 } else {
1510                         index := uint16(sa[j+len(sn)+1]) | uint16(sa[j+len(sn)])<<8
1511                         // one of them must be reset to nil,
1512                         // and the index updated appropriately to the other one
1513                         if x[i].nis == x[index].nis {
1514                         } else if x[i].nis < x[index].nis {
1515                                 sa[j+len(sn)], sa[j+len(sn)+1] = byte(ui>>8), byte(ui)
1516                                 if x[index].ready() {
1517                                         x[index].flagClr(structFieldInfoFlagReady)
1518                                         n--
1519                                 }
1520                         } else {
1521                                 if x[i].ready() {
1522                                         x[i].flagClr(structFieldInfoFlagReady)
1523                                         n--
1524                                 }
1525                         }
1526                 }
1527
1528         }
1529         var w []structFieldInfo
1530         sharingArray := len(x) <= typeInfoLoadArraySfisLen // sharing array with typeInfoLoadArray
1531         if sharingArray {
1532                 w = make([]structFieldInfo, n)
1533         }
1534
1535         // remove all the nils (non-ready)
1536         y = make([]*structFieldInfo, n)
1537         n = 0
1538         var sslen int
1539         for i := range x {
1540                 if !x[i].ready() {
1541                         continue
1542                 }
1543                 if !anyOmitEmpty && x[i].omitEmpty() {
1544                         anyOmitEmpty = true
1545                 }
1546                 if sharingArray {
1547                         w[n] = x[i]
1548                         y[n] = &w[n]
1549                 } else {
1550                         y[n] = &x[i]
1551                 }
1552                 sslen = sslen + len(x[i].encName) + 4
1553                 n++
1554         }
1555         if n != len(y) {
1556                 panicv.errorf("failure reading struct %v - expecting %d of %d valid fields, got %d",
1557                         rt, len(y), len(x), n)
1558         }
1559
1560         z = make([]*structFieldInfo, len(y))
1561         copy(z, y)
1562         sort.Sort(sfiSortedByEncName(z))
1563
1564         sharingArray = len(sa) <= typeInfoLoadArraySfiidxLen
1565         if sharingArray {
1566                 ss = make([]byte, 0, sslen)
1567         } else {
1568                 ss = sa[:0] // reuse the newly made sa array if necessary
1569         }
1570         for i := range z {
1571                 xn = z[i].encName
1572                 sep = tiSep(xn)
1573                 ui = uint16(i)
1574                 ss = append(ss, sep)
1575                 ss = append(ss, xn...)
1576                 ss = append(ss, 0xff, byte(ui>>8), byte(ui))
1577         }
1578         return
1579 }
1580
1581 func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) {
1582         return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp)
1583 }
1584
1585 // isEmptyStruct is only called from isEmptyValue, and checks if a struct is empty:
1586 //    - does it implement IsZero() bool
1587 //    - is it comparable, and can i compare directly using ==
1588 //    - if checkStruct, then walk through the encodable fields
1589 //      and check if they are empty or not.
1590 func isEmptyStruct(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool {
1591         // v is a struct kind - no need to check again.
1592         // We only check isZero on a struct kind, to reduce the amount of times
1593         // that we lookup the rtid and typeInfo for each type as we walk the tree.
1594
1595         vt := v.Type()
1596         rtid := rt2id(vt)
1597         if tinfos == nil {
1598                 tinfos = defTypeInfos
1599         }
1600         ti := tinfos.get(rtid, vt)
1601         if ti.rtid == timeTypId {
1602                 return rv2i(v).(time.Time).IsZero()
1603         }
1604         if ti.isFlag(typeInfoFlagIsZeroerPtr) && v.CanAddr() {
1605                 return rv2i(v.Addr()).(isZeroer).IsZero()
1606         }
1607         if ti.isFlag(typeInfoFlagIsZeroer) {
1608                 return rv2i(v).(isZeroer).IsZero()
1609         }
1610         if ti.isFlag(typeInfoFlagComparable) {
1611                 return rv2i(v) == rv2i(reflect.Zero(vt))
1612         }
1613         if !checkStruct {
1614                 return false
1615         }
1616         // We only care about what we can encode/decode,
1617         // so that is what we use to check omitEmpty.
1618         for _, si := range ti.sfiSrc {
1619                 sfv, valid := si.field(v, false)
1620                 if valid && !isEmptyValue(sfv, tinfos, deref, checkStruct) {
1621                         return false
1622                 }
1623         }
1624         return true
1625 }
1626
1627 // func roundFloat(x float64) float64 {
1628 //      t := math.Trunc(x)
1629 //      if math.Abs(x-t) >= 0.5 {
1630 //              return t + math.Copysign(1, x)
1631 //      }
1632 //      return t
1633 // }
1634
1635 func panicToErr(h errDecorator, err *error) {
1636         // Note: This method MUST be called directly from defer i.e. defer panicToErr ...
1637         // else it seems the recover is not fully handled
1638         if recoverPanicToErr {
1639                 if x := recover(); x != nil {
1640                         // fmt.Printf("panic'ing with: %v\n", x)
1641                         // debug.PrintStack()
1642                         panicValToErr(h, x, err)
1643                 }
1644         }
1645 }
1646
1647 func panicValToErr(h errDecorator, v interface{}, err *error) {
1648         switch xerr := v.(type) {
1649         case nil:
1650         case error:
1651                 switch xerr {
1652                 case nil:
1653                 case io.EOF, io.ErrUnexpectedEOF, errEncoderNotInitialized, errDecoderNotInitialized:
1654                         // treat as special (bubble up)
1655                         *err = xerr
1656                 default:
1657                         h.wrapErr(xerr, err)
1658                 }
1659         case string:
1660                 if xerr != "" {
1661                         h.wrapErr(xerr, err)
1662                 }
1663         case fmt.Stringer:
1664                 if xerr != nil {
1665                         h.wrapErr(xerr, err)
1666                 }
1667         default:
1668                 h.wrapErr(v, err)
1669         }
1670 }
1671
1672 func isImmutableKind(k reflect.Kind) (v bool) {
1673         return immutableKindsSet[k]
1674 }
1675
1676 // ----
1677
1678 type codecFnInfo struct {
1679         ti    *typeInfo
1680         xfFn  Ext
1681         xfTag uint64
1682         seq   seqType
1683         addrD bool
1684         addrF bool // if addrD, this says whether decode function can take a value or a ptr
1685         addrE bool
1686         ready bool // ready to use
1687 }
1688
1689 // codecFn encapsulates the captured variables and the encode function.
1690 // This way, we only do some calculations one times, and pass to the
1691 // code block that should be called (encapsulated in a function)
1692 // instead of executing the checks every time.
1693 type codecFn struct {
1694         i  codecFnInfo
1695         fe func(*Encoder, *codecFnInfo, reflect.Value)
1696         fd func(*Decoder, *codecFnInfo, reflect.Value)
1697         _  [1]uint64 // padding
1698 }
1699
1700 type codecRtidFn struct {
1701         rtid uintptr
1702         fn   *codecFn
1703 }
1704
1705 type codecFner struct {
1706         // hh Handle
1707         h  *BasicHandle
1708         s  []codecRtidFn
1709         be bool
1710         js bool
1711         _  [6]byte   // padding
1712         _  [3]uint64 // padding
1713 }
1714
1715 func (c *codecFner) reset(hh Handle) {
1716         bh := hh.getBasicHandle()
1717         // only reset iff extensions changed or *TypeInfos changed
1718         var hhSame = true &&
1719                 c.h == bh && c.h.TypeInfos == bh.TypeInfos &&
1720                 len(c.h.extHandle) == len(bh.extHandle) &&
1721                 (len(c.h.extHandle) == 0 || &c.h.extHandle[0] == &bh.extHandle[0])
1722         if !hhSame {
1723                 // c.hh = hh
1724                 c.h, bh = bh, c.h // swap both
1725                 _, c.js = hh.(*JsonHandle)
1726                 c.be = hh.isBinary()
1727                 if len(c.s) > 0 {
1728                         c.s = c.s[:0]
1729                 }
1730                 // for i := range c.s {
1731                 //      c.s[i].fn.i.ready = false
1732                 // }
1733         }
1734 }
1735
1736 func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
1737         rtid := rt2id(rt)
1738
1739         for _, x := range c.s {
1740                 if x.rtid == rtid {
1741                         // if rtid exists, then there's a *codenFn attached (non-nil)
1742                         fn = x.fn
1743                         if fn.i.ready {
1744                                 return
1745                         }
1746                         break
1747                 }
1748         }
1749         var ti *typeInfo
1750         if fn == nil {
1751                 fn = new(codecFn)
1752                 if c.s == nil {
1753                         c.s = make([]codecRtidFn, 0, 8)
1754                 }
1755                 c.s = append(c.s, codecRtidFn{rtid, fn})
1756         } else {
1757                 ti = fn.i.ti
1758                 *fn = codecFn{}
1759                 fn.i.ti = ti
1760                 // fn.fe, fn.fd = nil, nil
1761         }
1762         fi := &(fn.i)
1763         fi.ready = true
1764         if ti == nil {
1765                 ti = c.h.getTypeInfo(rtid, rt)
1766                 fi.ti = ti
1767         }
1768
1769         rk := reflect.Kind(ti.kind)
1770
1771         if checkCodecSelfer && (ti.cs || ti.csp) {
1772                 fn.fe = (*Encoder).selferMarshal
1773                 fn.fd = (*Decoder).selferUnmarshal
1774                 fi.addrF = true
1775                 fi.addrD = ti.csp
1776                 fi.addrE = ti.csp
1777         } else if rtid == timeTypId && !c.h.TimeNotBuiltin {
1778                 fn.fe = (*Encoder).kTime
1779                 fn.fd = (*Decoder).kTime
1780         } else if rtid == rawTypId {
1781                 fn.fe = (*Encoder).raw
1782                 fn.fd = (*Decoder).raw
1783         } else if rtid == rawExtTypId {
1784                 fn.fe = (*Encoder).rawExt
1785                 fn.fd = (*Decoder).rawExt
1786                 fi.addrF = true
1787                 fi.addrD = true
1788                 fi.addrE = true
1789         } else if xfFn := c.h.getExt(rtid); xfFn != nil {
1790                 fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
1791                 fn.fe = (*Encoder).ext
1792                 fn.fd = (*Decoder).ext
1793                 fi.addrF = true
1794                 fi.addrD = true
1795                 if rk == reflect.Struct || rk == reflect.Array {
1796                         fi.addrE = true
1797                 }
1798         } else if supportMarshalInterfaces && c.be && (ti.bm || ti.bmp) && (ti.bu || ti.bup) {
1799                 fn.fe = (*Encoder).binaryMarshal
1800                 fn.fd = (*Decoder).binaryUnmarshal
1801                 fi.addrF = true
1802                 fi.addrD = ti.bup
1803                 fi.addrE = ti.bmp
1804         } else if supportMarshalInterfaces && !c.be && c.js && (ti.jm || ti.jmp) && (ti.ju || ti.jup) {
1805                 //If JSON, we should check JSONMarshal before textMarshal
1806                 fn.fe = (*Encoder).jsonMarshal
1807                 fn.fd = (*Decoder).jsonUnmarshal
1808                 fi.addrF = true
1809                 fi.addrD = ti.jup
1810                 fi.addrE = ti.jmp
1811         } else if supportMarshalInterfaces && !c.be && (ti.tm || ti.tmp) && (ti.tu || ti.tup) {
1812                 fn.fe = (*Encoder).textMarshal
1813                 fn.fd = (*Decoder).textUnmarshal
1814                 fi.addrF = true
1815                 fi.addrD = ti.tup
1816                 fi.addrE = ti.tmp
1817         } else {
1818                 if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
1819                         if ti.pkgpath == "" { // un-named slice or map
1820                                 if idx := fastpathAV.index(rtid); idx != -1 {
1821                                         fn.fe = fastpathAV[idx].encfn
1822                                         fn.fd = fastpathAV[idx].decfn
1823                                         fi.addrD = true
1824                                         fi.addrF = false
1825                                 }
1826                         } else {
1827                                 // use mapping for underlying type if there
1828                                 var rtu reflect.Type
1829                                 if rk == reflect.Map {
1830                                         rtu = reflect.MapOf(ti.key, ti.elem)
1831                                 } else {
1832                                         rtu = reflect.SliceOf(ti.elem)
1833                                 }
1834                                 rtuid := rt2id(rtu)
1835                                 if idx := fastpathAV.index(rtuid); idx != -1 {
1836                                         xfnf := fastpathAV[idx].encfn
1837                                         xrt := fastpathAV[idx].rt
1838                                         fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
1839                                                 xfnf(e, xf, xrv.Convert(xrt))
1840                                         }
1841                                         fi.addrD = true
1842                                         fi.addrF = false // meaning it can be an address(ptr) or a value
1843                                         xfnf2 := fastpathAV[idx].decfn
1844                                         fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
1845                                                 if xrv.Kind() == reflect.Ptr {
1846                                                         xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
1847                                                 } else {
1848                                                         xfnf2(d, xf, xrv.Convert(xrt))
1849                                                 }
1850                                         }
1851                                 }
1852                         }
1853                 }
1854                 if fn.fe == nil && fn.fd == nil {
1855                         switch rk {
1856                         case reflect.Bool:
1857                                 fn.fe = (*Encoder).kBool
1858                                 fn.fd = (*Decoder).kBool
1859                         case reflect.String:
1860                                 fn.fe = (*Encoder).kString
1861                                 fn.fd = (*Decoder).kString
1862                         case reflect.Int:
1863                                 fn.fd = (*Decoder).kInt
1864                                 fn.fe = (*Encoder).kInt
1865                         case reflect.Int8:
1866                                 fn.fe = (*Encoder).kInt8
1867                                 fn.fd = (*Decoder).kInt8
1868                         case reflect.Int16:
1869                                 fn.fe = (*Encoder).kInt16
1870                                 fn.fd = (*Decoder).kInt16
1871                         case reflect.Int32:
1872                                 fn.fe = (*Encoder).kInt32
1873                                 fn.fd = (*Decoder).kInt32
1874                         case reflect.Int64:
1875                                 fn.fe = (*Encoder).kInt64
1876                                 fn.fd = (*Decoder).kInt64
1877                         case reflect.Uint:
1878                                 fn.fd = (*Decoder).kUint
1879                                 fn.fe = (*Encoder).kUint
1880                         case reflect.Uint8:
1881                                 fn.fe = (*Encoder).kUint8
1882                                 fn.fd = (*Decoder).kUint8
1883                         case reflect.Uint16:
1884                                 fn.fe = (*Encoder).kUint16
1885                                 fn.fd = (*Decoder).kUint16
1886                         case reflect.Uint32:
1887                                 fn.fe = (*Encoder).kUint32
1888                                 fn.fd = (*Decoder).kUint32
1889                         case reflect.Uint64:
1890                                 fn.fe = (*Encoder).kUint64
1891                                 fn.fd = (*Decoder).kUint64
1892                         case reflect.Uintptr:
1893                                 fn.fe = (*Encoder).kUintptr
1894                                 fn.fd = (*Decoder).kUintptr
1895                         case reflect.Float32:
1896                                 fn.fe = (*Encoder).kFloat32
1897                                 fn.fd = (*Decoder).kFloat32
1898                         case reflect.Float64:
1899                                 fn.fe = (*Encoder).kFloat64
1900                                 fn.fd = (*Decoder).kFloat64
1901                         case reflect.Invalid:
1902                                 fn.fe = (*Encoder).kInvalid
1903                                 fn.fd = (*Decoder).kErr
1904                         case reflect.Chan:
1905                                 fi.seq = seqTypeChan
1906                                 fn.fe = (*Encoder).kSlice
1907                                 fn.fd = (*Decoder).kSlice
1908                         case reflect.Slice:
1909                                 fi.seq = seqTypeSlice
1910                                 fn.fe = (*Encoder).kSlice
1911                                 fn.fd = (*Decoder).kSlice
1912                         case reflect.Array:
1913                                 fi.seq = seqTypeArray
1914                                 fn.fe = (*Encoder).kSlice
1915                                 fi.addrF = false
1916                                 fi.addrD = false
1917                                 rt2 := reflect.SliceOf(ti.elem)
1918                                 fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
1919                                         d.cfer().get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
1920                                 }
1921                                 // fn.fd = (*Decoder).kArray
1922                         case reflect.Struct:
1923                                 if ti.anyOmitEmpty || ti.mf || ti.mfp {
1924                                         fn.fe = (*Encoder).kStruct
1925                                 } else {
1926                                         fn.fe = (*Encoder).kStructNoOmitempty
1927                                 }
1928                                 fn.fd = (*Decoder).kStruct
1929                         case reflect.Map:
1930                                 fn.fe = (*Encoder).kMap
1931                                 fn.fd = (*Decoder).kMap
1932                         case reflect.Interface:
1933                                 // encode: reflect.Interface are handled already by preEncodeValue
1934                                 fn.fd = (*Decoder).kInterface
1935                                 fn.fe = (*Encoder).kErr
1936                         default:
1937                                 // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
1938                                 fn.fe = (*Encoder).kErr
1939                                 fn.fd = (*Decoder).kErr
1940                         }
1941                 }
1942         }
1943         return
1944 }
1945
1946 type codecFnPooler struct {
1947         cf  *codecFner
1948         cfp *sync.Pool
1949         hh  Handle
1950 }
1951
1952 func (d *codecFnPooler) cfer() *codecFner {
1953         if d.cf == nil {
1954                 var v interface{}
1955                 d.cfp, v = pool.codecFner()
1956                 d.cf = v.(*codecFner)
1957                 d.cf.reset(d.hh)
1958         }
1959         return d.cf
1960 }
1961
1962 func (d *codecFnPooler) alwaysAtEnd() {
1963         if d.cf != nil {
1964                 d.cfp.Put(d.cf)
1965                 d.cf, d.cfp = nil, nil
1966         }
1967 }
1968
1969 // ----
1970
1971 // these "checkOverflow" functions must be inlinable, and not call anybody.
1972 // Overflow means that the value cannot be represented without wrapping/overflow.
1973 // Overflow=false does not mean that the value can be represented without losing precision
1974 // (especially for floating point).
1975
1976 type checkOverflow struct{}
1977
1978 // func (checkOverflow) Float16(f float64) (overflow bool) {
1979 //      panicv.errorf("unimplemented")
1980 //      if f < 0 {
1981 //              f = -f
1982 //      }
1983 //      return math.MaxFloat32 < f && f <= math.MaxFloat64
1984 // }
1985
1986 func (checkOverflow) Float32(v float64) (overflow bool) {
1987         if v < 0 {
1988                 v = -v
1989         }
1990         return math.MaxFloat32 < v && v <= math.MaxFloat64
1991 }
1992 func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
1993         if bitsize == 0 || bitsize >= 64 || v == 0 {
1994                 return
1995         }
1996         if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
1997                 overflow = true
1998         }
1999         return
2000 }
2001 func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
2002         if bitsize == 0 || bitsize >= 64 || v == 0 {
2003                 return
2004         }
2005         if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
2006                 overflow = true
2007         }
2008         return
2009 }
2010 func (checkOverflow) SignedInt(v uint64) (overflow bool) {
2011         //e.g. -127 to 128 for int8
2012         pos := (v >> 63) == 0
2013         ui2 := v & 0x7fffffffffffffff
2014         if pos {
2015                 if ui2 > math.MaxInt64 {
2016                         overflow = true
2017                 }
2018         } else {
2019                 if ui2 > math.MaxInt64-1 {
2020                         overflow = true
2021                 }
2022         }
2023         return
2024 }
2025
2026 func (x checkOverflow) Float32V(v float64) float64 {
2027         if x.Float32(v) {
2028                 panicv.errorf("float32 overflow: %v", v)
2029         }
2030         return v
2031 }
2032 func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 {
2033         if x.Uint(v, bitsize) {
2034                 panicv.errorf("uint64 overflow: %v", v)
2035         }
2036         return v
2037 }
2038 func (x checkOverflow) IntV(v int64, bitsize uint8) int64 {
2039         if x.Int(v, bitsize) {
2040                 panicv.errorf("int64 overflow: %v", v)
2041         }
2042         return v
2043 }
2044 func (x checkOverflow) SignedIntV(v uint64) int64 {
2045         if x.SignedInt(v) {
2046                 panicv.errorf("uint64 to int64 overflow: %v", v)
2047         }
2048         return int64(v)
2049 }
2050
2051 // ------------------ SORT -----------------
2052
2053 func isNaN(f float64) bool { return f != f }
2054
2055 // -----------------------
2056
2057 type ioFlusher interface {
2058         Flush() error
2059 }
2060
2061 type ioPeeker interface {
2062         Peek(int) ([]byte, error)
2063 }
2064
2065 type ioBuffered interface {
2066         Buffered() int
2067 }
2068
2069 // -----------------------
2070
2071 type intSlice []int64
2072 type uintSlice []uint64
2073
2074 // type uintptrSlice []uintptr
2075 type floatSlice []float64
2076 type boolSlice []bool
2077 type stringSlice []string
2078
2079 // type bytesSlice [][]byte
2080
2081 func (p intSlice) Len() int           { return len(p) }
2082 func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
2083 func (p intSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2084
2085 func (p uintSlice) Len() int           { return len(p) }
2086 func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
2087 func (p uintSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2088
2089 // func (p uintptrSlice) Len() int           { return len(p) }
2090 // func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] }
2091 // func (p uintptrSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2092
2093 func (p floatSlice) Len() int { return len(p) }
2094 func (p floatSlice) Less(i, j int) bool {
2095         return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
2096 }
2097 func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
2098
2099 func (p stringSlice) Len() int           { return len(p) }
2100 func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
2101 func (p stringSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2102
2103 // func (p bytesSlice) Len() int           { return len(p) }
2104 // func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
2105 // func (p bytesSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2106
2107 func (p boolSlice) Len() int           { return len(p) }
2108 func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
2109 func (p boolSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2110
2111 // ---------------------
2112
2113 type sfiRv struct {
2114         v *structFieldInfo
2115         r reflect.Value
2116 }
2117
2118 type intRv struct {
2119         v int64
2120         r reflect.Value
2121 }
2122 type intRvSlice []intRv
2123 type uintRv struct {
2124         v uint64
2125         r reflect.Value
2126 }
2127 type uintRvSlice []uintRv
2128 type floatRv struct {
2129         v float64
2130         r reflect.Value
2131 }
2132 type floatRvSlice []floatRv
2133 type boolRv struct {
2134         v bool
2135         r reflect.Value
2136 }
2137 type boolRvSlice []boolRv
2138 type stringRv struct {
2139         v string
2140         r reflect.Value
2141 }
2142 type stringRvSlice []stringRv
2143 type bytesRv struct {
2144         v []byte
2145         r reflect.Value
2146 }
2147 type bytesRvSlice []bytesRv
2148 type timeRv struct {
2149         v time.Time
2150         r reflect.Value
2151 }
2152 type timeRvSlice []timeRv
2153
2154 func (p intRvSlice) Len() int           { return len(p) }
2155 func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
2156 func (p intRvSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2157
2158 func (p uintRvSlice) Len() int           { return len(p) }
2159 func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
2160 func (p uintRvSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2161
2162 func (p floatRvSlice) Len() int { return len(p) }
2163 func (p floatRvSlice) Less(i, j int) bool {
2164         return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
2165 }
2166 func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
2167
2168 func (p stringRvSlice) Len() int           { return len(p) }
2169 func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
2170 func (p stringRvSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2171
2172 func (p bytesRvSlice) Len() int           { return len(p) }
2173 func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
2174 func (p bytesRvSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2175
2176 func (p boolRvSlice) Len() int           { return len(p) }
2177 func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
2178 func (p boolRvSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2179
2180 func (p timeRvSlice) Len() int           { return len(p) }
2181 func (p timeRvSlice) Less(i, j int) bool { return p[i].v.Before(p[j].v) }
2182 func (p timeRvSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2183
2184 // -----------------
2185
2186 type bytesI struct {
2187         v []byte
2188         i interface{}
2189 }
2190
2191 type bytesISlice []bytesI
2192
2193 func (p bytesISlice) Len() int           { return len(p) }
2194 func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
2195 func (p bytesISlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
2196
2197 // -----------------
2198
2199 type set []uintptr
2200
2201 func (s *set) add(v uintptr) (exists bool) {
2202         // e.ci is always nil, or len >= 1
2203         x := *s
2204         if x == nil {
2205                 x = make([]uintptr, 1, 8)
2206                 x[0] = v
2207                 *s = x
2208                 return
2209         }
2210         // typically, length will be 1. make this perform.
2211         if len(x) == 1 {
2212                 if j := x[0]; j == 0 {
2213                         x[0] = v
2214                 } else if j == v {
2215                         exists = true
2216                 } else {
2217                         x = append(x, v)
2218                         *s = x
2219                 }
2220                 return
2221         }
2222         // check if it exists
2223         for _, j := range x {
2224                 if j == v {
2225                         exists = true
2226                         return
2227                 }
2228         }
2229         // try to replace a "deleted" slot
2230         for i, j := range x {
2231                 if j == 0 {
2232                         x[i] = v
2233                         return
2234                 }
2235         }
2236         // if unable to replace deleted slot, just append it.
2237         x = append(x, v)
2238         *s = x
2239         return
2240 }
2241
2242 func (s *set) remove(v uintptr) (exists bool) {
2243         x := *s
2244         if len(x) == 0 {
2245                 return
2246         }
2247         if len(x) == 1 {
2248                 if x[0] == v {
2249                         x[0] = 0
2250                 }
2251                 return
2252         }
2253         for i, j := range x {
2254                 if j == v {
2255                         exists = true
2256                         x[i] = 0 // set it to 0, as way to delete it.
2257                         // copy(x[i:], x[i+1:])
2258                         // x = x[:len(x)-1]
2259                         return
2260                 }
2261         }
2262         return
2263 }
2264
2265 // ------
2266
2267 // bitset types are better than [256]bool, because they permit the whole
2268 // bitset array being on a single cache line and use less memory.
2269
2270 // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
2271 // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
2272
2273 type bitset256 [32]byte
2274
2275 func (x *bitset256) isset(pos byte) bool {
2276         return x[pos>>3]&(1<<(pos&7)) != 0
2277 }
2278 func (x *bitset256) issetv(pos byte) byte {
2279         return x[pos>>3] & (1 << (pos & 7))
2280 }
2281 func (x *bitset256) set(pos byte) {
2282         x[pos>>3] |= (1 << (pos & 7))
2283 }
2284
2285 // func (x *bitset256) unset(pos byte) {
2286 //      x[pos>>3] &^= (1 << (pos & 7))
2287 // }
2288
2289 type bitset128 [16]byte
2290
2291 func (x *bitset128) isset(pos byte) bool {
2292         return x[pos>>3]&(1<<(pos&7)) != 0
2293 }
2294 func (x *bitset128) set(pos byte) {
2295         x[pos>>3] |= (1 << (pos & 7))
2296 }
2297
2298 // func (x *bitset128) unset(pos byte) {
2299 //      x[pos>>3] &^= (1 << (pos & 7))
2300 // }
2301
2302 type bitset32 [4]byte
2303
2304 func (x *bitset32) isset(pos byte) bool {
2305         return x[pos>>3]&(1<<(pos&7)) != 0
2306 }
2307 func (x *bitset32) set(pos byte) {
2308         x[pos>>3] |= (1 << (pos & 7))
2309 }
2310
2311 // func (x *bitset32) unset(pos byte) {
2312 //      x[pos>>3] &^= (1 << (pos & 7))
2313 // }
2314
2315 // type bit2set256 [64]byte
2316
2317 // func (x *bit2set256) set(pos byte, v1, v2 bool) {
2318 //      var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6
2319 //      if v1 {
2320 //              x[pos>>2] |= 1 << (pos2 + 1)
2321 //      }
2322 //      if v2 {
2323 //              x[pos>>2] |= 1 << pos2
2324 //      }
2325 // }
2326 // func (x *bit2set256) get(pos byte) uint8 {
2327 //      var pos2 uint8 = (pos & 3) << 1     // returning 0, 2, 4 or 6
2328 //      return x[pos>>2] << (6 - pos2) >> 6 // 11000000 -> 00000011
2329 // }
2330
2331 // ------------
2332
2333 type pooler struct {
2334         dn                                          sync.Pool // for decNaked
2335         cfn                                         sync.Pool // for codecFner
2336         tiload                                      sync.Pool
2337         strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool // for stringRV
2338 }
2339
2340 func (p *pooler) init() {
2341         p.strRv8.New = func() interface{} { return new([8]sfiRv) }
2342         p.strRv16.New = func() interface{} { return new([16]sfiRv) }
2343         p.strRv32.New = func() interface{} { return new([32]sfiRv) }
2344         p.strRv64.New = func() interface{} { return new([64]sfiRv) }
2345         p.strRv128.New = func() interface{} { return new([128]sfiRv) }
2346         p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
2347         p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
2348         p.cfn.New = func() interface{} { return new(codecFner) }
2349 }
2350
2351 func (p *pooler) sfiRv8() (sp *sync.Pool, v interface{}) {
2352         return &p.strRv8, p.strRv8.Get()
2353 }
2354 func (p *pooler) sfiRv16() (sp *sync.Pool, v interface{}) {
2355         return &p.strRv16, p.strRv16.Get()
2356 }
2357 func (p *pooler) sfiRv32() (sp *sync.Pool, v interface{}) {
2358         return &p.strRv32, p.strRv32.Get()
2359 }
2360 func (p *pooler) sfiRv64() (sp *sync.Pool, v interface{}) {
2361         return &p.strRv64, p.strRv64.Get()
2362 }
2363 func (p *pooler) sfiRv128() (sp *sync.Pool, v interface{}) {
2364         return &p.strRv128, p.strRv128.Get()
2365 }
2366 func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
2367         return &p.dn, p.dn.Get()
2368 }
2369 func (p *pooler) codecFner() (sp *sync.Pool, v interface{}) {
2370         return &p.cfn, p.cfn.Get()
2371 }
2372 func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
2373         return &p.tiload, p.tiload.Get()
2374 }
2375
2376 // func (p *pooler) decNaked() (v *decNaked, f func(*decNaked) ) {
2377 //      sp := &(p.dn)
2378 //      vv := sp.Get()
2379 //      return vv.(*decNaked), func(x *decNaked) { sp.Put(vv) }
2380 // }
2381 // func (p *pooler) decNakedGet() (v interface{}) {
2382 //      return p.dn.Get()
2383 // }
2384 // func (p *pooler) codecFnerGet() (v interface{}) {
2385 //      return p.cfn.Get()
2386 // }
2387 // func (p *pooler) tiLoadGet() (v interface{}) {
2388 //      return p.tiload.Get()
2389 // }
2390 // func (p *pooler) decNakedPut(v interface{}) {
2391 //      p.dn.Put(v)
2392 // }
2393 // func (p *pooler) codecFnerPut(v interface{}) {
2394 //      p.cfn.Put(v)
2395 // }
2396 // func (p *pooler) tiLoadPut(v interface{}) {
2397 //      p.tiload.Put(v)
2398 // }
2399
2400 type panicHdl struct{}
2401
2402 func (panicHdl) errorv(err error) {
2403         if err != nil {
2404                 panic(err)
2405         }
2406 }
2407
2408 func (panicHdl) errorstr(message string) {
2409         if message != "" {
2410                 panic(message)
2411         }
2412 }
2413
2414 func (panicHdl) errorf(format string, params ...interface{}) {
2415         if format != "" {
2416                 if len(params) == 0 {
2417                         panic(format)
2418                 } else {
2419                         panic(fmt.Sprintf(format, params...))
2420                 }
2421         }
2422 }
2423
2424 type errDecorator interface {
2425         wrapErr(in interface{}, out *error)
2426 }
2427
2428 type errDecoratorDef struct{}
2429
2430 func (errDecoratorDef) wrapErr(v interface{}, e *error) { *e = fmt.Errorf("%v", v) }
2431
2432 type must struct{}
2433
2434 func (must) String(s string, err error) string {
2435         if err != nil {
2436                 panicv.errorv(err)
2437         }
2438         return s
2439 }
2440 func (must) Int(s int64, err error) int64 {
2441         if err != nil {
2442                 panicv.errorv(err)
2443         }
2444         return s
2445 }
2446 func (must) Uint(s uint64, err error) uint64 {
2447         if err != nil {
2448                 panicv.errorv(err)
2449         }
2450         return s
2451 }
2452 func (must) Float(s float64, err error) float64 {
2453         if err != nil {
2454                 panicv.errorv(err)
2455         }
2456         return s
2457 }
2458
2459 // xdebugf prints the message in red on the terminal.
2460 // Use it in place of fmt.Printf (which it calls internally)
2461 func xdebugf(pattern string, args ...interface{}) {
2462         var delim string
2463         if len(pattern) > 0 && pattern[len(pattern)-1] != '\n' {
2464                 delim = "\n"
2465         }
2466         fmt.Printf("\033[1;31m"+pattern+delim+"\033[0m", args...)
2467 }
2468
2469 // func isImmutableKind(k reflect.Kind) (v bool) {
2470 //      return false ||
2471 //              k == reflect.Int ||
2472 //              k == reflect.Int8 ||
2473 //              k == reflect.Int16 ||
2474 //              k == reflect.Int32 ||
2475 //              k == reflect.Int64 ||
2476 //              k == reflect.Uint ||
2477 //              k == reflect.Uint8 ||
2478 //              k == reflect.Uint16 ||
2479 //              k == reflect.Uint32 ||
2480 //              k == reflect.Uint64 ||
2481 //              k == reflect.Uintptr ||
2482 //              k == reflect.Float32 ||
2483 //              k == reflect.Float64 ||
2484 //              k == reflect.Bool ||
2485 //              k == reflect.String
2486 // }
2487
2488 // func timeLocUTCName(tzint int16) string {
2489 //      if tzint == 0 {
2490 //              return "UTC"
2491 //      }
2492 //      var tzname = []byte("UTC+00:00")
2493 //      //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf. inline below.
2494 //      //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first
2495 //      var tzhr, tzmin int16
2496 //      if tzint < 0 {
2497 //              tzname[3] = '-' // (TODO: verify. this works here)
2498 //              tzhr, tzmin = -tzint/60, (-tzint)%60
2499 //      } else {
2500 //              tzhr, tzmin = tzint/60, tzint%60
2501 //      }
2502 //      tzname[4] = timeDigits[tzhr/10]
2503 //      tzname[5] = timeDigits[tzhr%10]
2504 //      tzname[7] = timeDigits[tzmin/10]
2505 //      tzname[8] = timeDigits[tzmin%10]
2506 //      return string(tzname)
2507 //      //return time.FixedZone(string(tzname), int(tzint)*60)
2508 // }