/
helper.go
2414 lines (2134 loc) · 64.2 KB
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
// Contains code shared by both encode and decode.
// Some shared ideas around encoding/decoding
// ------------------------------------------
//
// If an interface{} is passed, we first do a type assertion to see if it is
// a primitive type or a map/slice of primitive types, and use a fastpath to handle it.
//
// If we start with a reflect.Value, we are already in reflect.Value land and
// will try to grab the function for the underlying Type and directly call that function.
// This is more performant than calling reflect.Value.Interface().
//
// This still helps us bypass many layers of reflection, and give best performance.
//
// Containers
// ------------
// Containers in the stream are either associative arrays (key-value pairs) or
// regular arrays (indexed by incrementing integers).
//
// Some streams support indefinite-length containers, and use a breaking
// byte-sequence to denote that the container has come to an end.
//
// Some streams also are text-based, and use explicit separators to denote the
// end/beginning of different values.
//
// During encode, we use a high-level condition to determine how to iterate through
// the container. That decision is based on whether the container is text-based (with
// separators) or binary (without separators). If binary, we do not even call the
// encoding of separators.
//
// During decode, we use a different high-level condition to determine how to iterate
// through the containers. That decision is based on whether the stream contained
// a length prefix, or if it used explicit breaks. If length-prefixed, we assume that
// it has to be binary, and we do not even try to read separators.
//
// Philosophy
// ------------
// On decode, this codec will update containers appropriately:
// - If struct, update fields from stream into fields of struct.
// If field in stream not found in struct, handle appropriately (based on option).
// If a struct field has no corresponding value in the stream, leave it AS IS.
// If nil in stream, set value to nil/zero value.
// - If map, update map from stream.
// If the stream value is NIL, set the map to nil.
// - if slice, try to update up to length of array in stream.
// if container len is less than stream array length,
// and container cannot be expanded, handled (based on option).
// This means you can decode 4-element stream array into 1-element array.
//
// ------------------------------------
// On encode, user can specify omitEmpty. This means that the value will be omitted
// if the zero value. The problem may occur during decode, where omitted values do not affect
// the value being decoded into. This means that if decoding into a struct with an
// int field with current value=5, and the field is omitted in the stream, then after
// decoding, the value will still be 5 (not 0).
// omitEmpty only works if you guarantee that you always decode into zero-values.
//
// ------------------------------------
// We could have truncated a map to remove keys not available in the stream,
// or set values in the struct which are not in the stream to their zero values.
// We decided against it because there is no efficient way to do it.
// We may introduce it as an option later.
// However, that will require enabling it for both runtime and code generation modes.
//
// To support truncate, we need to do 2 passes over the container:
// map
// - first collect all keys (e.g. in k1)
// - for each key in stream, mark k1 that the key should not be removed
// - after updating map, do second pass and call delete for all keys in k1 which are not marked
// struct:
// - for each field, track the *typeInfo s1
// - iterate through all s1, and for each one not marked, set value to zero
// - this involves checking the possible anonymous fields which are nil ptrs.
// too much work.
//
// ------------------------------------------
// Error Handling is done within the library using panic.
//
// This way, the code doesn't have to keep checking if an error has happened,
// and we don't have to keep sending the error value along with each call
// or storing it in the En|Decoder and checking it constantly along the way.
//
// The disadvantage is that small functions which use panics cannot be inlined.
// The code accounts for that by only using panics behind an interface;
// since interface calls cannot be inlined, this is irrelevant.
//
// We considered storing the error is En|Decoder.
// - once it has its err field set, it cannot be used again.
// - panicing will be optional, controlled by const flag.
// - code should always check error first and return early.
// We eventually decided against it as it makes the code clumsier to always
// check for these error conditions.
import (
"bytes"
"encoding"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
scratchByteArrayLen = 32
// initCollectionCap = 16 // 32 is defensive. 16 is preferred.
// Support encoding.(Binary|Text)(Unm|M)arshaler.
// This constant flag will enable or disable it.
supportMarshalInterfaces = true
// for debugging, set this to false, to catch panic traces.
// Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
recoverPanicToErr = true
// arrayCacheLen is the length of the cache used in encoder or decoder for
// allowing zero-alloc initialization.
arrayCacheLen = 8
// size of the cacheline: defaulting to value for archs: amd64, arm64, 386
// should use "runtime/internal/sys".CacheLineSize, but that is not exposed.
cacheLineSize = 64
wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize
wordSize = wordSizeBits / 8
maxLevelsEmbedding = 15 // use this, so structFieldInfo fits into 8 bytes
)
var (
oneByteArr = [1]byte{0}
zeroByteSlice = oneByteArr[:0:0]
)
var refBitset bitset32
var pool pooler
var panicv panicHdl
func init() {
pool.init()
refBitset.set(byte(reflect.Map))
refBitset.set(byte(reflect.Ptr))
refBitset.set(byte(reflect.Func))
refBitset.set(byte(reflect.Chan))
}
type charEncoding uint8
const (
cRAW charEncoding = iota
cUTF8
cUTF16LE
cUTF16BE
cUTF32LE
cUTF32BE
)
// valueType is the stream type
type valueType uint8
const (
valueTypeUnset valueType = iota
valueTypeNil
valueTypeInt
valueTypeUint
valueTypeFloat
valueTypeBool
valueTypeString
valueTypeSymbol
valueTypeBytes
valueTypeMap
valueTypeArray
valueTypeTime
valueTypeExt
// valueTypeInvalid = 0xff
)
var valueTypeStrings = [...]string{
"Unset",
"Nil",
"Int",
"Uint",
"Float",
"Bool",
"String",
"Symbol",
"Bytes",
"Map",
"Array",
"Timestamp",
"Ext",
}
func (x valueType) String() string {
if int(x) < len(valueTypeStrings) {
return valueTypeStrings[x]
}
return strconv.FormatInt(int64(x), 10)
}
type seqType uint8
const (
_ seqType = iota
seqTypeArray
seqTypeSlice
seqTypeChan
)
// note that containerMapStart and containerArraySend are not sent.
// This is because the ReadXXXStart and EncodeXXXStart already does these.
type containerState uint8
const (
_ containerState = iota
containerMapStart // slot left open, since Driver method already covers it
containerMapKey
containerMapValue
containerMapEnd
containerArrayStart // slot left open, since Driver methods already cover it
containerArrayElem
containerArrayEnd
)
// // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
// type sfiIdx struct {
// name string
// index int
// }
// do not recurse if a containing type refers to an embedded type
// which refers back to its containing type (via a pointer).
// The second time this back-reference happens, break out,
// so as not to cause an infinite loop.
const rgetMaxRecursion = 2
// Anecdotally, we believe most types have <= 12 fields.
// - even Java's PMD rules set TooManyFields threshold to 15.
// However, go has embedded fields, which should be regarded as
// top level, allowing structs to possibly double or triple.
// In addition, we don't want to keep creating transient arrays,
// especially for the sfi index tracking, and the evtypes tracking.
//
// So - try to keep typeInfoLoadArray within 2K bytes
const (
typeInfoLoadArraySfisLen = 16
typeInfoLoadArraySfiidxLen = 8 * 112
typeInfoLoadArrayEtypesLen = 12
typeInfoLoadArrayBLen = 8 * 4
)
type typeInfoLoad struct {
// fNames []string
// encNames []string
etypes []uintptr
sfis []structFieldInfo
}
type typeInfoLoadArray struct {
// fNames [typeInfoLoadArrayLen]string
// encNames [typeInfoLoadArrayLen]string
sfis [typeInfoLoadArraySfisLen]structFieldInfo
sfiidx [typeInfoLoadArraySfiidxLen]byte
etypes [typeInfoLoadArrayEtypesLen]uintptr
b [typeInfoLoadArrayBLen]byte // scratch - used for struct field names
}
// mirror json.Marshaler and json.Unmarshaler here,
// so we don't import the encoding/json package
type jsonMarshaler interface {
MarshalJSON() ([]byte, error)
}
type jsonUnmarshaler interface {
UnmarshalJSON([]byte) error
}
type isZeroer interface {
IsZero() bool
}
// type byteAccepter func(byte) bool
var (
bigen = binary.BigEndian
structInfoFieldName = "_struct"
mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
intfSliceTyp = reflect.TypeOf([]interface{}(nil))
intfTyp = intfSliceTyp.Elem()
reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem()
stringTyp = reflect.TypeOf("")
timeTyp = reflect.TypeOf(time.Time{})
rawExtTyp = reflect.TypeOf(RawExt{})
rawTyp = reflect.TypeOf(Raw{})
uintptrTyp = reflect.TypeOf(uintptr(0))
uint8Typ = reflect.TypeOf(uint8(0))
uint8SliceTyp = reflect.TypeOf([]uint8(nil))
uintTyp = reflect.TypeOf(uint(0))
intTyp = reflect.TypeOf(int(0))
mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem()
uint8TypId = rt2id(uint8Typ)
uint8SliceTypId = rt2id(uint8SliceTyp)
rawExtTypId = rt2id(rawExtTyp)
rawTypId = rt2id(rawTyp)
intfTypId = rt2id(intfTyp)
timeTypId = rt2id(timeTyp)
stringTypId = rt2id(stringTyp)
mapStrIntfTypId = rt2id(mapStrIntfTyp)
mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
intfSliceTypId = rt2id(intfSliceTyp)
// mapBySliceTypId = rt2id(mapBySliceTyp)
intBitsize = uint8(intTyp.Bits())
uintBitsize = uint8(uintTyp.Bits())
bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
chkOvf checkOverflow
errNoFieldNameToStructFieldInfo = errors.New("no field name passed to parseStructFieldInfo")
)
var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
var immutableKindsSet = [32]bool{
// reflect.Invalid: ,
reflect.Bool: true,
reflect.Int: true,
reflect.Int8: true,
reflect.Int16: true,
reflect.Int32: true,
reflect.Int64: true,
reflect.Uint: true,
reflect.Uint8: true,
reflect.Uint16: true,
reflect.Uint32: true,
reflect.Uint64: true,
reflect.Uintptr: true,
reflect.Float32: true,
reflect.Float64: true,
reflect.Complex64: true,
reflect.Complex128: true,
// reflect.Array
// reflect.Chan
// reflect.Func: true,
// reflect.Interface
// reflect.Map
// reflect.Ptr
// reflect.Slice
reflect.String: true,
// reflect.Struct
// reflect.UnsafePointer
}
// Selfer defines methods by which a value can encode or decode itself.
//
// Any type which implements Selfer will be able to encode or decode itself.
// Consequently, during (en|de)code, this takes precedence over
// (text|binary)(M|Unm)arshal or extension support.
//
// Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
// This is because, during each decode, we first check the the next set of bytes
// represent nil, and if so, we just set the value to nil.
type Selfer interface {
CodecEncodeSelf(*Encoder)
CodecDecodeSelf(*Decoder)
}
// MapBySlice is a tag interface that denotes wrapped slice should encode as a map in the stream.
// The slice contains a sequence of key-value pairs.
// This affords storing a map in a specific sequence in the stream.
//
// Example usage:
// type T1 []string // or []int or []Point or any other "slice" type
// func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map
// type T2 struct { KeyValues T1 }
//
// var kvs = []string{"one", "1", "two", "2", "three", "3"}
// var v2 = T2{ KeyValues: T1(kvs) }
// // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} }
//
// The support of MapBySlice affords the following:
// - A slice type which implements MapBySlice will be encoded as a map
// - A slice can be decoded from a map in the stream
// - It MUST be a slice type (not a pointer receiver) that implements MapBySlice
type MapBySlice interface {
MapBySlice()
}
// BasicHandle encapsulates the common options and extension functions.
//
// Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
type BasicHandle struct {
// BasicHandle is always a part of a different type.
// It doesn't have to fit into it own cache lines.
// TypeInfos is used to get the type info for any type.
//
// If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
TypeInfos *TypeInfos
// Note: BasicHandle is not comparable, due to these slices here (extHandle, intf2impls).
// If *[]T is used instead, this becomes comparable, at the cost of extra indirection.
// Thses slices are used all the time, so keep as slices (not pointers).
extHandle
intf2impls
RPCOptions
// ---- cache line
DecodeOptions
// ---- cache line
EncodeOptions
// noBuiltInTypeChecker
}
func (x *BasicHandle) getBasicHandle() *BasicHandle {
return x
}
func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
if x.TypeInfos == nil {
return defTypeInfos.get(rtid, rt)
}
return x.TypeInfos.get(rtid, rt)
}
// Handle is the interface for a specific encoding format.
//
// Typically, a Handle is pre-configured before first time use,
// and not modified while in use. Such a pre-configured Handle
// is safe for concurrent access.
type Handle interface {
Name() string
getBasicHandle() *BasicHandle
recreateEncDriver(encDriver) bool
newEncDriver(w *Encoder) encDriver
newDecDriver(r *Decoder) decDriver
isBinary() bool
hasElemSeparators() bool
// IsBuiltinType(rtid uintptr) bool
}
// Raw represents raw formatted bytes.
// We "blindly" store it during encode and retrieve the raw bytes during decode.
// Note: it is dangerous during encode, so we may gate the behaviour
// behind an Encode flag which must be explicitly set.
type Raw []byte
// RawExt represents raw unprocessed extension data.
// Some codecs will decode extension data as a *RawExt
// if there is no registered extension for the tag.
//
// Only one of Data or Value is nil.
// If Data is nil, then the content of the RawExt is in the Value.
type RawExt struct {
Tag uint64
// Data is the []byte which represents the raw ext. If nil, ext is exposed in Value.
// Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types
Data []byte
// Value represents the extension, if Data is nil.
// Value is used by codecs (e.g. cbor, json) which leverage the format to do
// custom serialization of the types.
Value interface{}
}
// BytesExt handles custom (de)serialization of types to/from []byte.
// It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
type BytesExt interface {
// WriteExt converts a value to a []byte.
//
// Note: v is a pointer iff the registered extension type is a struct or array kind.
WriteExt(v interface{}) []byte
// ReadExt updates a value from a []byte.
//
// Note: dst is always a pointer kind to the registered extension type.
ReadExt(dst interface{}, src []byte)
}
// InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
// The Encoder or Decoder will then handle the further (de)serialization of that known type.
//
// It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types.
type InterfaceExt interface {
// ConvertExt converts a value into a simpler interface for easy encoding
// e.g. convert time.Time to int64.
//
// Note: v is a pointer iff the registered extension type is a struct or array kind.
ConvertExt(v interface{}) interface{}
// UpdateExt updates a value from a simpler interface for easy decoding
// e.g. convert int64 to time.Time.
//
// Note: dst is always a pointer kind to the registered extension type.
UpdateExt(dst interface{}, src interface{})
}
// Ext handles custom (de)serialization of custom types / extensions.
type Ext interface {
BytesExt
InterfaceExt
}
// addExtWrapper is a wrapper implementation to support former AddExt exported method.
type addExtWrapper struct {
encFn func(reflect.Value) ([]byte, error)
decFn func(reflect.Value, []byte) error
}
func (x addExtWrapper) WriteExt(v interface{}) []byte {
bs, err := x.encFn(reflect.ValueOf(v))
if err != nil {
panic(err)
}
return bs
}
func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
panic(err)
}
}
func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
return x.WriteExt(v)
}
func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
x.ReadExt(dest, v.([]byte))
}
type extWrapper struct {
BytesExt
InterfaceExt
}
type bytesExtFailer struct{}
func (bytesExtFailer) WriteExt(v interface{}) []byte {
panicv.errorstr("BytesExt.WriteExt is not supported")
return nil
}
func (bytesExtFailer) ReadExt(v interface{}, bs []byte) {
panicv.errorstr("BytesExt.ReadExt is not supported")
}
type interfaceExtFailer struct{}
func (interfaceExtFailer) ConvertExt(v interface{}) interface{} {
panicv.errorstr("InterfaceExt.ConvertExt is not supported")
return nil
}
func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) {
panicv.errorstr("InterfaceExt.UpdateExt is not supported")
}
type binaryEncodingType struct{}
func (binaryEncodingType) isBinary() bool { return true }
type textEncodingType struct{}
func (textEncodingType) isBinary() bool { return false }
// noBuiltInTypes is embedded into many types which do not support builtins
// e.g. msgpack, simple, cbor.
// type noBuiltInTypeChecker struct{}
// func (noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
// type noBuiltInTypes struct{ noBuiltInTypeChecker }
type noBuiltInTypes struct{}
func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
// type noStreamingCodec struct{}
// func (noStreamingCodec) CheckBreak() bool { return false }
// func (noStreamingCodec) hasElemSeparators() bool { return false }
type noElemSeparators struct{}
func (noElemSeparators) hasElemSeparators() (v bool) { return }
func (noElemSeparators) recreateEncDriver(e encDriver) (v bool) { return }
// bigenHelper.
// Users must already slice the x completely, because we will not reslice.
type bigenHelper struct {
x []byte // must be correctly sliced to appropriate len. slicing is a cost.
w encWriter
}
func (z bigenHelper) writeUint16(v uint16) {
bigen.PutUint16(z.x, v)
z.w.writeb(z.x)
}
func (z bigenHelper) writeUint32(v uint32) {
bigen.PutUint32(z.x, v)
z.w.writeb(z.x)
}
func (z bigenHelper) writeUint64(v uint64) {
bigen.PutUint64(z.x, v)
z.w.writeb(z.x)
}
type extTypeTagFn struct {
rtid uintptr
rtidptr uintptr
rt reflect.Type
tag uint64
ext Ext
_ [1]uint64 // padding
}
type extHandle []extTypeTagFn
// AddExt registes an encode and decode function for a reflect.Type.
// To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
//
// Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
func (o *extHandle) AddExt(rt reflect.Type, tag byte,
encfn func(reflect.Value) ([]byte, error),
decfn func(reflect.Value, []byte) error) (err error) {
if encfn == nil || decfn == nil {
return o.SetExt(rt, uint64(tag), nil)
}
return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
}
// SetExt will set the extension for a tag and reflect.Type.
// Note that the type must be a named type, and specifically not a pointer or Interface.
// An error is returned if that is not honored.
// To Deregister an ext, call SetExt with nil Ext.
//
// Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
// o is a pointer, because we may need to initialize it
rk := rt.Kind()
for rk == reflect.Ptr {
rt = rt.Elem()
rk = rt.Kind()
}
if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr {
return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt)
}
rtid := rt2id(rt)
switch rtid {
case timeTypId, rawTypId, rawExtTypId:
// all natively supported type, so cannot have an extension
return // TODO: should we silently ignore, or return an error???
}
// if o == nil {
// return errors.New("codec.Handle.SetExt: extHandle not initialized")
// }
o2 := *o
// if o2 == nil {
// return errors.New("codec.Handle.SetExt: extHandle not initialized")
// }
for i := range o2 {
v := &o2[i]
if v.rtid == rtid {
v.tag, v.ext = tag, ext
return
}
}
rtidptr := rt2id(reflect.PtrTo(rt))
*o = append(o2, extTypeTagFn{rtid, rtidptr, rt, tag, ext, [1]uint64{}})
return
}
func (o extHandle) getExt(rtid uintptr) (v *extTypeTagFn) {
for i := range o {
v = &o[i]
if v.rtid == rtid || v.rtidptr == rtid {
return
}
}
return nil
}
func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) {
for i := range o {
v = &o[i]
if v.tag == tag {
return
}
}
return nil
}
type intf2impl struct {
rtid uintptr // for intf
impl reflect.Type
// _ [1]uint64 // padding // not-needed, as *intf2impl is never returned.
}
type intf2impls []intf2impl
// Intf2Impl maps an interface to an implementing type.
// This allows us support infering the concrete type
// and populating it when passed an interface.
// e.g. var v io.Reader can be decoded as a bytes.Buffer, etc.
//
// Passing a nil impl will clear the mapping.
func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) {
if impl != nil && !impl.Implements(intf) {
return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf)
}
rtid := rt2id(intf)
o2 := *o
for i := range o2 {
v := &o2[i]
if v.rtid == rtid {
v.impl = impl
return
}
}
*o = append(o2, intf2impl{rtid, impl})
return
}
func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) {
for i := range o {
v := &o[i]
if v.rtid == rtid {
if v.impl == nil {
return
}
if v.impl.Kind() == reflect.Ptr {
return reflect.New(v.impl.Elem())
}
return reflect.New(v.impl).Elem()
}
}
return
}
type structFieldInfoFlag uint8
const (
_ structFieldInfoFlag = 1 << iota
structFieldInfoFlagReady
structFieldInfoFlagOmitEmpty
)
func (x *structFieldInfoFlag) flagSet(f structFieldInfoFlag) {
*x = *x | f
}
func (x *structFieldInfoFlag) flagClr(f structFieldInfoFlag) {
*x = *x &^ f
}
func (x structFieldInfoFlag) flagGet(f structFieldInfoFlag) bool {
return x&f != 0
}
func (x structFieldInfoFlag) omitEmpty() bool {
return x.flagGet(structFieldInfoFlagOmitEmpty)
}
func (x structFieldInfoFlag) ready() bool {
return x.flagGet(structFieldInfoFlagReady)
}
type structFieldInfo struct {
encName string // encode name
fieldName string // field name
is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
nis uint8 // num levels of embedding. if 1, then it's not embedded.
structFieldInfoFlag
}
func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
if v, valid := si.field(v, false); valid {
v.Set(reflect.Zero(v.Type()))
}
}
// rv returns the field of the struct.
// If anonymous, it returns an Invalid
func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
// replicate FieldByIndex
for i, x := range si.is {
if uint8(i) == si.nis {
break
}
if v, valid = baseStructRv(v, update); !valid {
return
}
v = v.Field(int(x))
}
return v, true
}
// func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
// v, _ = si.field(v, update)
// return v
// }
func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) {
keytype = valueTypeString // default
if stag == "" {
return
}
for i, s := range strings.Split(stag, ",") {
if i == 0 {
} else {
switch s {
case "omitempty":
omitEmpty = true
case "toarray":
toArray = true
case "int":
keytype = valueTypeInt
case "uint":
keytype = valueTypeUint
case "float":
keytype = valueTypeFloat
// case "bool":
// keytype = valueTypeBool
case "string":
keytype = valueTypeString
}
}
}
return
}
func (si *structFieldInfo) parseTag(stag string) {
// if fname == "" {
// panic(errNoFieldNameToStructFieldInfo)
// }
if stag == "" {
return
}
for i, s := range strings.Split(stag, ",") {
if i == 0 {
if s != "" {
si.encName = s
}
} else {
switch s {
case "omitempty":
si.flagSet(structFieldInfoFlagOmitEmpty)
// si.omitEmpty = true
// case "toarray":
// si.toArray = true
}
}
}
}
type sfiSortedByEncName []*structFieldInfo
func (p sfiSortedByEncName) Len() int {
return len(p)
}
func (p sfiSortedByEncName) Less(i, j int) bool {
return p[i].encName < p[j].encName
}
func (p sfiSortedByEncName) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
const structFieldNodeNumToCache = 4
type structFieldNodeCache struct {
rv [structFieldNodeNumToCache]reflect.Value
idx [structFieldNodeNumToCache]uint32
num uint8
}
func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
for i, k := range &x.idx {
if uint8(i) == x.num {
return // break
}
if key == k {
return x.rv[i], true
}
}
return
}
func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
if x.num < structFieldNodeNumToCache {
x.rv[x.num] = fv
x.idx[x.num] = key
x.num++
return
}
}
type structFieldNode struct {
v reflect.Value
cache2 structFieldNodeCache
cache3 structFieldNodeCache
update bool
}
func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
// return si.fieldval(x.v, x.update)
// Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
// This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
var valid bool
switch si.nis {
case 1:
fv = x.v.Field(int(si.is[0]))
case 2:
if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
fv = fv.Field(int(si.is[1]))
return
}
fv = x.v.Field(int(si.is[0]))
if fv, valid = baseStructRv(fv, x.update); !valid {
return
}
x.cache2.tryAdd(fv, uint32(si.is[0]))
fv = fv.Field(int(si.is[1]))
case 3:
var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
if fv, valid = x.cache3.get(key); valid {
fv = fv.Field(int(si.is[2]))
return
}
fv = x.v.Field(int(si.is[0]))
if fv, valid = baseStructRv(fv, x.update); !valid {
return
}
fv = fv.Field(int(si.is[1]))
if fv, valid = baseStructRv(fv, x.update); !valid {
return
}
x.cache3.tryAdd(fv, key)
fv = fv.Field(int(si.is[2]))
default:
fv, _ = si.field(x.v, x.update)
}
return
}
func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
for v.Kind() == reflect.Ptr {
if v.IsNil() {
if !update {
return
}
v.Set(reflect.New(v.Type().Elem()))
}