-
Notifications
You must be signed in to change notification settings - Fork 296
/
encode.go
1526 lines (1360 loc) · 40.1 KB
/
encode.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-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"encoding"
"errors"
"io"
"reflect"
"sort"
"strconv"
"time"
)
// defEncByteBufSize is the default size of []byte used
// for bufio buffer or []byte (when nil passed)
const defEncByteBufSize = 1 << 10 // 4:16, 6:64, 8:256, 10:1024
var errEncoderNotInitialized = errors.New("Encoder not initialized")
// encDriver abstracts the actual codec (binc vs msgpack, etc)
type encDriver interface {
EncodeNil()
EncodeInt(i int64)
EncodeUint(i uint64)
EncodeBool(b bool)
EncodeFloat32(f float32)
EncodeFloat64(f float64)
EncodeRawExt(re *RawExt)
EncodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext)
// EncodeString using cUTF8, honor'ing StringToRaw flag
EncodeString(v string)
EncodeStringBytesRaw(v []byte)
EncodeTime(time.Time)
WriteArrayStart(length int)
WriteArrayEnd()
WriteMapStart(length int)
WriteMapEnd()
// reset will reset current encoding runtime state, and cached information from the handle
reset()
encoder() *Encoder
driverStateManager
}
type encDriverContainerTracker interface {
WriteArrayElem()
WriteMapElemKey()
WriteMapElemValue()
}
type encDriverNoState struct{}
func (encDriverNoState) captureState() interface{} { return nil }
func (encDriverNoState) reset() {}
func (encDriverNoState) resetState() {}
func (encDriverNoState) restoreState(v interface{}) {}
type encDriverNoopContainerWriter struct{}
func (encDriverNoopContainerWriter) WriteArrayStart(length int) {}
func (encDriverNoopContainerWriter) WriteArrayEnd() {}
func (encDriverNoopContainerWriter) WriteMapStart(length int) {}
func (encDriverNoopContainerWriter) WriteMapEnd() {}
// encStructFieldObj[Slice] is used for sorting when there are missing fields and canonical flag is set
type encStructFieldObj struct {
key string
rv reflect.Value
intf interface{}
ascii bool
isRv bool
}
type encStructFieldObjSlice []encStructFieldObj
func (p encStructFieldObjSlice) Len() int { return len(p) }
func (p encStructFieldObjSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p encStructFieldObjSlice) Less(i, j int) bool {
return p[uint(i)].key < p[uint(j)].key
}
// EncodeOptions captures configuration options during encode.
type EncodeOptions struct {
// WriterBufferSize is the size of the buffer used when writing.
//
// if > 0, we use a smart buffer internally for performance purposes.
WriterBufferSize int
// ChanRecvTimeout is the timeout used when selecting from a chan.
//
// Configuring this controls how we receive from a chan during the encoding process.
// - If ==0, we only consume the elements currently available in the chan.
// - if <0, we consume until the chan is closed.
// - If >0, we consume until this timeout.
ChanRecvTimeout time.Duration
// StructToArray specifies to encode a struct as an array, and not as a map
StructToArray bool
// Canonical representation means that encoding a value will always result in the same
// sequence of bytes.
//
// This only affects maps, as the iteration order for maps is random.
//
// The implementation MAY use the natural sort order for the map keys if possible:
//
// - If there is a natural sort order (ie for number, bool, string or []byte keys),
// then the map keys are first sorted in natural order and then written
// with corresponding map values to the strema.
// - If there is no natural sort order, then the map keys will first be
// encoded into []byte, and then sorted,
// before writing the sorted keys and the corresponding map values to the stream.
//
Canonical bool
// CheckCircularRef controls whether we check for circular references
// and error fast during an encode.
//
// If enabled, an error is received if a pointer to a struct
// references itself either directly or through one of its fields (iteratively).
//
// This is opt-in, as there may be a performance hit to checking circular references.
CheckCircularRef bool
// RecursiveEmptyCheck controls how we determine whether a value is empty.
//
// If true, we descend into interfaces and pointers to reursively check if value is empty.
//
// We *might* check struct fields one by one to see if empty
// (if we cannot directly check if a struct value is equal to its zero value).
// If so, we honor IsZero, Comparable, IsCodecEmpty(), etc.
// Note: This *may* make OmitEmpty more expensive due to the large number of reflect calls.
//
// If false, we check if the value is equal to its zero value (newly allocated state).
RecursiveEmptyCheck bool
// Raw controls whether we encode Raw values.
// This is a "dangerous" option and must be explicitly set.
// If set, we blindly encode Raw values as-is, without checking
// if they are a correct representation of a value in that format.
// If unset, we error out.
Raw bool
// StringToRaw controls how strings are encoded.
//
// As a go string is just an (immutable) sequence of bytes,
// it can be encoded either as raw bytes or as a UTF string.
//
// By default, strings are encoded as UTF-8.
// but can be treated as []byte during an encode.
//
// Note that things which we know (by definition) to be UTF-8
// are ALWAYS encoded as UTF-8 strings.
// These include encoding.TextMarshaler, time.Format calls, struct field names, etc.
StringToRaw bool
// OptimumSize controls whether we optimize for the smallest size.
//
// Some formats will use this flag to determine whether to encode
// in the smallest size possible, even if it takes slightly longer.
//
// For example, some formats that support half-floats might check if it is possible
// to store a float64 as a half float. Doing this check has a small performance cost,
// but the benefit is that the encoded message will be smaller.
OptimumSize bool
// NoAddressableReadonly controls whether we try to force a non-addressable value
// to be addressable so we can call a pointer method on it e.g. for types
// that support Selfer, json.Marshaler, etc.
//
// Use it in the very rare occurrence that your types modify a pointer value when calling
// an encode callback function e.g. JsonMarshal, TextMarshal, BinaryMarshal or CodecEncodeSelf.
NoAddressableReadonly bool
}
// ---------------------------------------------
func (e *Encoder) rawExt(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeRawExt(rv2i(rv).(*RawExt))
}
func (e *Encoder) ext(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeExt(rv2i(rv), f.ti.rt, f.xfTag, f.xfFn)
}
func (e *Encoder) selferMarshal(f *codecFnInfo, rv reflect.Value) {
rv2i(rv).(Selfer).CodecEncodeSelf(e)
}
func (e *Encoder) binaryMarshal(f *codecFnInfo, rv reflect.Value) {
bs, fnerr := rv2i(rv).(encoding.BinaryMarshaler).MarshalBinary()
e.marshalRaw(bs, fnerr)
}
func (e *Encoder) textMarshal(f *codecFnInfo, rv reflect.Value) {
bs, fnerr := rv2i(rv).(encoding.TextMarshaler).MarshalText()
e.marshalUtf8(bs, fnerr)
}
func (e *Encoder) jsonMarshal(f *codecFnInfo, rv reflect.Value) {
bs, fnerr := rv2i(rv).(jsonMarshaler).MarshalJSON()
e.marshalAsis(bs, fnerr)
}
func (e *Encoder) raw(f *codecFnInfo, rv reflect.Value) {
e.rawBytes(rv2i(rv).(Raw))
}
func (e *Encoder) encodeComplex64(v complex64) {
if imag(v) != 0 {
e.errorf("cannot encode complex number: %v, with imaginary values: %v", v, imag(v))
}
e.e.EncodeFloat32(real(v))
}
func (e *Encoder) encodeComplex128(v complex128) {
if imag(v) != 0 {
e.errorf("cannot encode complex number: %v, with imaginary values: %v", v, imag(v))
}
e.e.EncodeFloat64(real(v))
}
func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeBool(rvGetBool(rv))
}
func (e *Encoder) kTime(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeTime(rvGetTime(rv))
}
func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeString(rvGetString(rv))
}
func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeFloat32(rvGetFloat32(rv))
}
func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeFloat64(rvGetFloat64(rv))
}
func (e *Encoder) kComplex64(f *codecFnInfo, rv reflect.Value) {
e.encodeComplex64(rvGetComplex64(rv))
}
func (e *Encoder) kComplex128(f *codecFnInfo, rv reflect.Value) {
e.encodeComplex128(rvGetComplex128(rv))
}
func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt(rv)))
}
func (e *Encoder) kInt8(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt8(rv)))
}
func (e *Encoder) kInt16(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt16(rv)))
}
func (e *Encoder) kInt32(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt32(rv)))
}
func (e *Encoder) kInt64(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt64(rv)))
}
func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint(rv)))
}
func (e *Encoder) kUint8(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint8(rv)))
}
func (e *Encoder) kUint16(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint16(rv)))
}
func (e *Encoder) kUint32(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint32(rv)))
}
func (e *Encoder) kUint64(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint64(rv)))
}
func (e *Encoder) kUintptr(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUintptr(rv)))
}
func (e *Encoder) kErr(f *codecFnInfo, rv reflect.Value) {
e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv)
}
func chanToSlice(rv reflect.Value, rtslice reflect.Type, timeout time.Duration) (rvcs reflect.Value) {
rvcs = rvZeroK(rtslice, reflect.Slice)
if timeout < 0 { // consume until close
for {
recv, recvOk := rv.Recv()
if !recvOk {
break
}
rvcs = reflect.Append(rvcs, recv)
}
} else {
cases := make([]reflect.SelectCase, 2)
cases[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: rv}
if timeout == 0 {
cases[1] = reflect.SelectCase{Dir: reflect.SelectDefault}
} else {
tt := time.NewTimer(timeout)
cases[1] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(tt.C)}
}
for {
chosen, recv, recvOk := reflect.Select(cases)
if chosen == 1 || !recvOk {
break
}
rvcs = reflect.Append(rvcs, recv)
}
}
return
}
func (e *Encoder) kSeqFn(rtelem reflect.Type) (fn *codecFn) {
for rtelem.Kind() == reflect.Ptr {
rtelem = rtelem.Elem()
}
// if kind is reflect.Interface, do not pre-determine the encoding type,
// because preEncodeValue may break it down to a concrete type and kInterface will bomb.
if rtelem.Kind() != reflect.Interface {
fn = e.h.fn(rtelem)
}
return
}
func (e *Encoder) kSliceWMbs(rv reflect.Value, ti *typeInfo) {
var l = rvLenSlice(rv)
if l == 0 {
e.mapStart(0)
} else {
e.haltOnMbsOddLen(l)
e.mapStart(l >> 1) // e.mapStart(l / 2)
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
if j&1 == 0 { // j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.encodeValue(rvSliceIndex(rv, j, ti), fn)
}
}
e.mapEnd()
}
func (e *Encoder) kSliceW(rv reflect.Value, ti *typeInfo) {
var l = rvLenSlice(rv)
e.arrayStart(l)
if l > 0 {
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
e.arrayElem()
e.encodeValue(rvSliceIndex(rv, j, ti), fn)
}
}
e.arrayEnd()
}
func (e *Encoder) kArrayWMbs(rv reflect.Value, ti *typeInfo) {
var l = rv.Len()
if l == 0 {
e.mapStart(0)
} else {
e.haltOnMbsOddLen(l)
e.mapStart(l >> 1) // e.mapStart(l / 2)
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
if j&1 == 0 { // j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.encodeValue(rv.Index(j), fn)
}
}
e.mapEnd()
}
func (e *Encoder) kArrayW(rv reflect.Value, ti *typeInfo) {
var l = rv.Len()
e.arrayStart(l)
if l > 0 {
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
e.arrayElem()
e.encodeValue(rv.Index(j), fn)
}
}
e.arrayEnd()
}
func (e *Encoder) kChan(f *codecFnInfo, rv reflect.Value) {
if f.ti.chandir&uint8(reflect.RecvDir) == 0 {
e.errorf("send-only channel cannot be encoded")
}
if !f.ti.mbs && uint8TypId == rt2id(f.ti.elem) {
e.kSliceBytesChan(rv)
return
}
rtslice := reflect.SliceOf(f.ti.elem)
rv = chanToSlice(rv, rtslice, e.h.ChanRecvTimeout)
ti := e.h.getTypeInfo(rt2id(rtslice), rtslice)
if f.ti.mbs {
e.kSliceWMbs(rv, ti)
} else {
e.kSliceW(rv, ti)
}
}
func (e *Encoder) kSlice(f *codecFnInfo, rv reflect.Value) {
if f.ti.mbs {
e.kSliceWMbs(rv, f.ti)
} else if f.ti.rtid == uint8SliceTypId || uint8TypId == rt2id(f.ti.elem) {
e.e.EncodeStringBytesRaw(rvGetBytes(rv))
} else {
e.kSliceW(rv, f.ti)
}
}
func (e *Encoder) kArray(f *codecFnInfo, rv reflect.Value) {
if f.ti.mbs {
e.kArrayWMbs(rv, f.ti)
} else if handleBytesWithinKArray && uint8TypId == rt2id(f.ti.elem) {
e.e.EncodeStringBytesRaw(rvGetArrayBytes(rv, []byte{}))
} else {
e.kArrayW(rv, f.ti)
}
}
func (e *Encoder) kSliceBytesChan(rv reflect.Value) {
// do not use range, so that the number of elements encoded
// does not change, and encoding does not hang waiting on someone to close chan.
bs0 := e.blist.peek(32, true)
bs := bs0
irv := rv2i(rv)
ch, ok := irv.(<-chan byte)
if !ok {
ch = irv.(chan byte)
}
L1:
switch timeout := e.h.ChanRecvTimeout; {
case timeout == 0: // only consume available
for {
select {
case b := <-ch:
bs = append(bs, b)
default:
break L1
}
}
case timeout > 0: // consume until timeout
tt := time.NewTimer(timeout)
for {
select {
case b := <-ch:
bs = append(bs, b)
case <-tt.C:
// close(tt.C)
break L1
}
}
default: // consume until close
for b := range ch {
bs = append(bs, b)
}
}
e.e.EncodeStringBytesRaw(bs)
e.blist.put(bs)
if !byteSliceSameData(bs0, bs) {
e.blist.put(bs0)
}
}
func (e *Encoder) kStructSfi(f *codecFnInfo) []*structFieldInfo {
if e.h.Canonical {
return f.ti.sfi.sorted()
}
return f.ti.sfi.source()
}
func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) {
var tisfi []*structFieldInfo
if f.ti.toArray || e.h.StructToArray { // toArray
tisfi = f.ti.sfi.source()
e.arrayStart(len(tisfi))
for _, si := range tisfi {
e.arrayElem()
e.encodeValue(si.path.field(rv), nil)
}
e.arrayEnd()
} else {
tisfi = e.kStructSfi(f)
e.mapStart(len(tisfi))
keytyp := f.ti.keyType
for _, si := range tisfi {
e.mapElemKey()
e.kStructFieldKey(keytyp, si.path.encNameAsciiAlphaNum, si.encName)
e.mapElemValue()
e.encodeValue(si.path.field(rv), nil)
}
e.mapEnd()
}
}
func (e *Encoder) kStructFieldKey(keyType valueType, encNameAsciiAlphaNum bool, encName string) {
encStructFieldKey(encName, e.e, e.w(), keyType, encNameAsciiAlphaNum, e.js)
}
func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) {
var newlen int
ti := f.ti
toMap := !(ti.toArray || e.h.StructToArray)
var mf map[string]interface{}
if ti.flagMissingFielder {
mf = rv2i(rv).(MissingFielder).CodecMissingFields()
toMap = true
newlen += len(mf)
} else if ti.flagMissingFielderPtr {
rv2 := e.addrRV(rv, ti.rt, ti.ptr)
mf = rv2i(rv2).(MissingFielder).CodecMissingFields()
toMap = true
newlen += len(mf)
}
tisfi := ti.sfi.source()
newlen += len(tisfi)
var fkvs = e.slist.get(newlen)[:newlen]
recur := e.h.RecursiveEmptyCheck
var kv sfiRv
var j int
if toMap {
newlen = 0
for _, si := range e.kStructSfi(f) {
kv.r = si.path.field(rv)
if si.path.omitEmpty && isEmptyValue(kv.r, e.h.TypeInfos, recur) {
continue
}
kv.v = si
fkvs[newlen] = kv
newlen++
}
var mf2s []stringIntf
if len(mf) > 0 {
mf2s = make([]stringIntf, 0, len(mf))
for k, v := range mf {
if k == "" {
continue
}
if ti.infoFieldOmitempty && isEmptyValue(reflect.ValueOf(v), e.h.TypeInfos, recur) {
continue
}
mf2s = append(mf2s, stringIntf{k, v})
}
}
e.mapStart(newlen + len(mf2s))
// When there are missing fields, and Canonical flag is set,
// we cannot have the missing fields and struct fields sorted independently.
// We have to capture them together and sort as a unit.
if len(mf2s) > 0 && e.h.Canonical {
mf2w := make([]encStructFieldObj, newlen+len(mf2s))
for j = 0; j < newlen; j++ {
kv = fkvs[j]
mf2w[j] = encStructFieldObj{kv.v.encName, kv.r, nil, kv.v.path.encNameAsciiAlphaNum, true}
}
for _, v := range mf2s {
mf2w[j] = encStructFieldObj{v.v, reflect.Value{}, v.i, false, false}
j++
}
sort.Sort((encStructFieldObjSlice)(mf2w))
for _, v := range mf2w {
e.mapElemKey()
e.kStructFieldKey(ti.keyType, v.ascii, v.key)
e.mapElemValue()
if v.isRv {
e.encodeValue(v.rv, nil)
} else {
e.encode(v.intf)
}
}
} else {
keytyp := ti.keyType
for j = 0; j < newlen; j++ {
kv = fkvs[j]
e.mapElemKey()
e.kStructFieldKey(keytyp, kv.v.path.encNameAsciiAlphaNum, kv.v.encName)
e.mapElemValue()
e.encodeValue(kv.r, nil)
}
for _, v := range mf2s {
e.mapElemKey()
e.kStructFieldKey(keytyp, false, v.v)
e.mapElemValue()
e.encode(v.i)
}
}
e.mapEnd()
} else {
newlen = len(tisfi)
for i, si := range tisfi { // use unsorted array (to match sequence in struct)
kv.r = si.path.field(rv)
// use the zero value.
// if a reference or struct, set to nil (so you do not output too much)
if si.path.omitEmpty && isEmptyValue(kv.r, e.h.TypeInfos, recur) {
switch kv.r.Kind() {
case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice:
kv.r = reflect.Value{} //encode as nil
}
}
fkvs[i] = kv
}
// encode it all
e.arrayStart(newlen)
for j = 0; j < newlen; j++ {
e.arrayElem()
e.encodeValue(fkvs[j].r, nil)
}
e.arrayEnd()
}
// do not use defer. Instead, use explicit pool return at end of function.
// defer has a cost we are trying to avoid.
// If there is a panic and these slices are not returned, it is ok.
e.slist.put(fkvs)
}
func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) {
l := rvLenMap(rv)
e.mapStart(l)
if l == 0 {
e.mapEnd()
return
}
// determine the underlying key and val encFn's for the map.
// This eliminates some work which is done for each loop iteration i.e.
// rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn.
//
// However, if kind is reflect.Interface, do not pre-determine the
// encoding type, because preEncodeValue may break it down to
// a concrete type and kInterface will bomb.
var keyFn, valFn *codecFn
ktypeKind := reflect.Kind(f.ti.keykind)
vtypeKind := reflect.Kind(f.ti.elemkind)
rtval := f.ti.elem
rtvalkind := vtypeKind
for rtvalkind == reflect.Ptr {
rtval = rtval.Elem()
rtvalkind = rtval.Kind()
}
if rtvalkind != reflect.Interface {
valFn = e.h.fn(rtval)
}
var rvv = mapAddrLoopvarRV(f.ti.elem, vtypeKind)
rtkey := f.ti.key
var keyTypeIsString = stringTypId == rt2id(rtkey) // rtkeyid
if keyTypeIsString {
keyFn = e.h.fn(rtkey)
} else {
for rtkey.Kind() == reflect.Ptr {
rtkey = rtkey.Elem()
}
if rtkey.Kind() != reflect.Interface {
keyFn = e.h.fn(rtkey)
}
}
if e.h.Canonical {
e.kMapCanonical(f.ti, rv, rvv, keyFn, valFn)
e.mapEnd()
return
}
var rvk = mapAddrLoopvarRV(f.ti.key, ktypeKind)
var it mapIter
mapRange(&it, rv, rvk, rvv, true)
for it.Next() {
e.mapElemKey()
if keyTypeIsString {
e.e.EncodeString(it.Key().String())
} else {
e.encodeValue(it.Key(), keyFn)
}
e.mapElemValue()
e.encodeValue(it.Value(), valFn)
}
it.Done()
e.mapEnd()
}
func (e *Encoder) kMapCanonical(ti *typeInfo, rv, rvv reflect.Value, keyFn, valFn *codecFn) {
// The base kind of the type of the map key is sufficient for ordering.
// We only do out of band if that kind is not ordered (number or string), bool or time.Time.
// If the key is a predeclared type, directly call methods on encDriver e.g. EncodeString
// but if not, call encodeValue, in case it has an extension registered or otherwise.
rtkey := ti.key
rtkeydecl := rtkey.PkgPath() == "" && rtkey.Name() != "" // key type is predeclared
mks := rv.MapKeys()
rtkeyKind := rtkey.Kind()
kfast := mapKeyFastKindFor(rtkeyKind)
visindirect := mapStoresElemIndirect(uintptr(ti.elemsize))
visref := refBitset.isset(ti.elemkind)
switch rtkeyKind {
case reflect.Bool:
// though bool keys make no sense in a map, it *could* happen.
// in that case, we MUST support it in reflection mode,
// as that is the fallback for even codecgen and others.
// sort the keys so that false comes before true
// ie if 2 keys in order (true, false), then swap them
if len(mks) == 2 && mks[0].Bool() {
mks[0], mks[1] = mks[1], mks[0]
}
for i := range mks {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeBool(mks[i].Bool())
} else {
e.encodeValueNonNil(mks[i], keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mks[i], rvv, kfast, visindirect, visref), valFn)
}
case reflect.String:
mksv := make([]stringRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.String()
}
sort.Sort(stringRvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeString(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
mksv := make([]uint64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Uint()
}
sort.Sort(uint64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeUint(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
mksv := make([]int64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Int()
}
sort.Sort(int64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeInt(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Float32:
mksv := make([]float64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Float()
}
sort.Sort(float64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeFloat32(float32(mksv[i].v))
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Float64:
mksv := make([]float64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Float()
}
sort.Sort(float64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeFloat64(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
default:
if rtkey == timeTyp {
mksv := make([]timeRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = rv2i(k).(time.Time)
}
sort.Sort(timeRvSlice(mksv))
for i := range mksv {
e.mapElemKey()
e.e.EncodeTime(mksv[i].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
break
}
// out-of-band
// first encode each key to a []byte first, then sort them, then record
bs0 := e.blist.get(len(mks) * 16)
mksv := bs0
mksbv := make([]bytesRv, len(mks))
func() {
// replicate sideEncode logic
defer func(wb bytesEncAppender, bytes bool, c containerState, state interface{}) {
e.wb = wb
e.bytes = bytes
e.c = c
e.e.restoreState(state)
}(e.wb, e.bytes, e.c, e.e.captureState())
// e2 := NewEncoderBytes(&mksv, e.hh)
e.wb = bytesEncAppender{mksv[:0], &mksv}
e.bytes = true
e.c = 0
e.e.resetState()
for i, k := range mks {
v := &mksbv[i]
l := len(mksv)
e.c = containerMapKey
e.encodeValue(k, nil)
e.atEndOfEncode()
e.w().end()
v.r = k
v.v = mksv[l:]
}
}()
sort.Sort(bytesRvSlice(mksbv))
for j := range mksbv {
e.mapElemKey()
e.encWr.writeb(mksbv[j].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksbv[j].r, rvv, kfast, visindirect, visref), valFn)
}
e.blist.put(mksv)
if !byteSliceSameData(bs0, mksv) {
e.blist.put(bs0)
}
}
}
// Encoder writes an object to an output stream in a supported format.
//
// Encoder is NOT safe for concurrent use i.e. a Encoder cannot be used
// concurrently in multiple goroutines.
//
// However, as Encoder could be allocation heavy to initialize, a Reset method is provided
// so its state can be reused to decode new input streams repeatedly.
// This is the idiomatic way to use.
type Encoder struct {
panicHdl
e encDriver
h *BasicHandle
// hopefully, reduce derefencing cost by laying the encWriter inside the Encoder
encWr
// ---- cpu cache line boundary
hh Handle
blist bytesFreelist
err error
// ---- cpu cache line boundary
// ---- writable fields during execution --- *try* to keep in sep cache line
// ci holds interfaces during an encoding (if CheckCircularRef=true)
//
// We considered using a []uintptr (slice of pointer addresses) retrievable via rv.UnsafeAddr.
// However, it is possible for the same pointer to point to 2 different types e.g.
// type T struct { tHelper }
// Here, for var v T; &v and &v.tHelper are the same pointer.
// Consequently, we need a tuple of type and pointer, which interface{} natively provides.
ci []interface{} // []uintptr
perType encPerType
slist sfiRvFreelist
}
// NewEncoder returns an Encoder for encoding into an io.Writer.
//
// For efficiency, Users are encouraged to configure WriterBufferSize on the handle
// OR pass in a memory buffered writer (eg bufio.Writer, bytes.Buffer).
func NewEncoder(w io.Writer, h Handle) *Encoder {
e := h.newEncDriver().encoder()
if w != nil {
e.Reset(w)
}
return e
}
// NewEncoderBytes returns an encoder for encoding directly and efficiently
// into a byte slice, using zero-copying to temporary slices.
//
// It will potentially replace the output byte slice pointed to.
// After encoding, the out parameter contains the encoded contents.
func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
e := h.newEncDriver().encoder()
if out != nil {
e.ResetBytes(out)
}
return e
}
func (e *Encoder) HandleName() string {
return e.hh.Name()
}
func (e *Encoder) init(h Handle) {
initHandle(h)
e.err = errEncoderNotInitialized
e.bytes = true
e.hh = h
e.h = h.getBasicHandle()
e.be = e.hh.isBinary()
}
func (e *Encoder) w() *encWr {