encode.go
34.9 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
// 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
import (
"encoding"
"errors"
"fmt"
"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{}, 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()
atEndOfEncode()
encoder() *Encoder
}
type encDriverContainerTracker interface {
WriteArrayElem()
WriteMapElemKey()
WriteMapElemValue()
}
type encodeError struct {
codecError
}
func (e encodeError) Error() string {
return fmt.Sprintf("%s encode error: %v", e.name, e.err)
}
type encDriverNoopContainerWriter struct{}
func (encDriverNoopContainerWriter) WriteArrayStart(length int) {}
func (encDriverNoopContainerWriter) WriteArrayEnd() {}
func (encDriverNoopContainerWriter) WriteMapStart(length int) {}
func (encDriverNoopContainerWriter) WriteMapEnd() {}
func (encDriverNoopContainerWriter) atEndOfEncode() {}
// 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 whether we descend into interfaces, structs and pointers
// when checking if a value is empty.
//
// Note that this may make OmitEmpty more expensive, as it incurs a lot more reflect calls.
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
// // AsSymbols defines what should be encoded as symbols.
// //
// // Encoding as symbols can reduce the encoded size significantly.
// //
// // However, during decoding, each string to be encoded as a symbol must
// // be checked to see if it has been seen before. Consequently, encoding time
// // will increase if using symbols, because string comparisons has a clear cost.
// //
// // Sample values:
// // AsSymbolNone
// // AsSymbolAll
// // AsSymbolMapStringKeys
// // AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag
// AsSymbols AsSymbolFlag
}
// ---------------------------------------------
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.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) 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) kFloat64(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeFloat64(rvGetFloat64(rv))
}
func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeFloat32(rvGetFloat32(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) kInvalid(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeNil()
}
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 = reflect.Zero(rtslice)
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: rv4i(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 = rvGetSliceLen(rv)
if l == 0 {
e.mapStart(0)
} else {
if l%2 == 1 {
e.errorf("mapBySlice requires even slice length, but got %v", l)
return
}
e.mapStart(l / 2)
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
if 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 = rvGetSliceLen(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) kSeqWMbs(rv reflect.Value, ti *typeInfo) {
var l = rv.Len()
if l == 0 {
e.mapStart(0)
} else {
if l%2 == 1 {
e.errorf("mapBySlice requires even slice length, but got %v", l)
return
}
e.mapStart(l / 2)
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.encodeValue(rv.Index(j), fn)
}
}
e.mapEnd()
}
func (e *Encoder) kSeqW(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 rvIsNil(rv) {
e.e.EncodeNil()
return
}
if f.ti.chandir&uint8(reflect.RecvDir) == 0 {
e.errorf("send-only channel cannot be encoded")
return
}
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 rvIsNil(rv) {
e.e.EncodeNil()
return
}
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.kSeqWMbs(rv, f.ti)
} else {
if uint8TypId == rt2id(f.ti.elem) {
e.e.EncodeStringBytesRaw(rvGetArrayBytesRO(rv, e.b[:]))
} else {
e.kSeqW(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.
// for b := range rv2i(rv).(<-chan byte) { bs = append(bs, b) }
// ch := rv2i(rv).(<-chan byte) // fix error - that this is a chan byte, not a <-chan byte.
bs := e.b[:0]
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)
}
func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) {
sfn := structFieldNode{v: rv, update: false}
if f.ti.toArray || e.h.StructToArray { // toArray
e.arrayStart(len(f.ti.sfiSrc))
for _, si := range f.ti.sfiSrc {
e.arrayElem()
e.encodeValue(sfn.field(si), nil)
}
e.arrayEnd()
} else {
e.mapStart(len(f.ti.sfiSort))
for _, si := range f.ti.sfiSort {
e.mapElemKey()
e.kStructFieldKey(f.ti.keyType, si.encNameAsciiAlphaNum, si.encName)
e.mapElemValue()
e.encodeValue(sfn.field(si), 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
toMap := !(f.ti.toArray || e.h.StructToArray)
var mf map[string]interface{}
if f.ti.isFlag(tiflagMissingFielder) {
mf = rv2i(rv).(MissingFielder).CodecMissingFields()
toMap = true
newlen += len(mf)
} else if f.ti.isFlag(tiflagMissingFielderPtr) {
if rv.CanAddr() {
mf = rv2i(rv.Addr()).(MissingFielder).CodecMissingFields()
} else {
// make a new addressable value of same one, and use it
rv2 := reflect.New(rv.Type())
rvSetDirect(rv2.Elem(), rv)
mf = rv2i(rv2).(MissingFielder).CodecMissingFields()
}
toMap = true
newlen += len(mf)
}
newlen += len(f.ti.sfiSrc)
var fkvs = e.slist.get(newlen)
recur := e.h.RecursiveEmptyCheck
sfn := structFieldNode{v: rv, update: false}
var kv sfiRv
var j int
if toMap {
newlen = 0
for _, si := range f.ti.sfiSort { // use sorted array
kv.r = sfn.field(si)
if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) {
continue
}
kv.v = si // si.encName
fkvs[newlen] = kv
newlen++
}
var mflen int
for k, v := range mf {
if k == "" {
delete(mf, k)
continue
}
if f.ti.infoFieldOmitempty && isEmptyValue(rv4i(v), e.h.TypeInfos, recur, recur) {
delete(mf, k)
continue
}
mflen++
}
// encode it all
e.mapStart(newlen + mflen)
for j = 0; j < newlen; j++ {
kv = fkvs[j]
e.mapElemKey()
e.kStructFieldKey(f.ti.keyType, kv.v.encNameAsciiAlphaNum, kv.v.encName)
e.mapElemValue()
e.encodeValue(kv.r, nil)
}
// now, add the others
for k, v := range mf {
e.mapElemKey()
e.kStructFieldKey(f.ti.keyType, false, k)
e.mapElemValue()
e.encode(v)
}
e.mapEnd()
} else {
newlen = len(f.ti.sfiSrc)
for i, si := range f.ti.sfiSrc { // use unsorted array (to match sequence in struct)
kv.r = sfn.field(si)
// use the zero value.
// if a reference or struct, set to nil (so you do not output too much)
if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, 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.
// spool.end()
e.slist.put(fkvs)
}
func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) {
if rvIsNil(rv) {
e.e.EncodeNil()
return
}
l := rv.Len()
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 := f.ti.key.Kind()
vtypeKind := f.ti.elem.Kind()
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 = mapAddressableRV(f.ti.elem, vtypeKind)
if e.h.Canonical {
e.kMapCanonical(f.ti.key, f.ti.elem, rv, rvv, valFn)
e.mapEnd()
return
}
rtkey := f.ti.key
var keyTypeIsString = stringTypId == rt2id(rtkey) // rtkeyid
if !keyTypeIsString {
for rtkey.Kind() == reflect.Ptr {
rtkey = rtkey.Elem()
}
if rtkey.Kind() != reflect.Interface {
keyFn = e.h.fn(rtkey)
}
}
var rvk = mapAddressableRV(f.ti.key, ktypeKind)
var it mapIter
mapRange(&it, rv, rvk, rvv, true)
validKV := it.ValidKV()
var vx reflect.Value
for it.Next() {
e.mapElemKey()
if validKV {
vx = it.Key()
} else {
vx = rvk
}
if keyTypeIsString {
e.e.EncodeString(vx.String())
} else {
e.encodeValue(vx, keyFn)
}
e.mapElemValue()
if validKV {
vx = it.Value()
} else {
vx = rvv
}
e.encodeValue(vx, valFn)
}
it.Done()
e.mapEnd()
}
func (e *Encoder) kMapCanonical(rtkey, rtval reflect.Type, rv, rvv reflect.Value, valFn *codecFn) {
// we previously did out-of-band if an extension was registered.
// This is not necessary, as the natural kind is sufficient for ordering.
mks := rv.MapKeys()
switch rtkey.Kind() {
case reflect.Bool:
mksv := make([]boolRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Bool()
}
sort.Sort(boolRvSlice(mksv))
for i := range mksv {
e.mapElemKey()
e.e.EncodeBool(mksv[i].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv), 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()
e.e.EncodeString(mksv[i].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv), 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()
e.e.EncodeUint(mksv[i].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv), 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()
e.e.EncodeInt(mksv[i].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv), 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()
e.e.EncodeFloat32(float32(mksv[i].v))
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv), 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()
e.e.EncodeFloat64(mksv[i].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
}
case reflect.Struct:
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), valFn)
}
break
}
fallthrough
default:
// out-of-band
// first encode each key to a []byte first, then sort them, then record
var mksv []byte = e.blist.get(len(mks) * 16)[:0]
e2 := NewEncoderBytes(&mksv, e.hh)
mksbv := make([]bytesRv, len(mks))
for i, k := range mks {
v := &mksbv[i]
l := len(mksv)
e2.MustEncode(k)
v.r = k
v.v = mksv[l:]
}
sort.Sort(bytesRvSlice(mksbv))
for j := range mksbv {
e.mapElemKey()
e.encWr.writeb(mksbv[j].v) // e.asis(mksbv[j].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksbv[j].r, rvv), valFn)
}
e.blist.put(mksv)
}
}
// 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 set // holds set of addresses found during an encoding (if CheckCircularRef=true)
slist sfiRvFreelist
b [(2 * 8)]byte // for encoding chan byte, (non-addressable) [N]byte, etc
// ---- cpu cache line boundary?
}
// 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()
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()
e.ResetBytes(out)
return e
}
func (e *Encoder) init(h Handle) {
e.err = errEncoderNotInitialized
e.bytes = true
e.hh = h
e.h = basicHandle(h)
e.be = e.hh.isBinary()
}
func (e *Encoder) w() *encWr {
return &e.encWr
}
func (e *Encoder) resetCommon() {
e.e.reset()
if e.ci == nil {
// e.ci = (set)(e.cidef[:0])
} else {
e.ci = e.ci[:0]
}
e.c = 0
e.err = nil
}
// Reset resets the Encoder with a new output stream.
//
// This accommodates using the state of the Encoder,
// where it has "cached" information about sub-engines.
func (e *Encoder) Reset(w io.Writer) {
if w == nil {
return
}
e.bytes = false
if e.wf == nil {
e.wf = new(bufioEncWriter)
}
e.wf.reset(w, e.h.WriterBufferSize, &e.blist)
e.resetCommon()
}
// ResetBytes resets the Encoder with a new destination output []byte.
func (e *Encoder) ResetBytes(out *[]byte) {
if out == nil {
return
}
var in []byte = *out
if in == nil {
in = make([]byte, defEncByteBufSize)
}
e.bytes = true
e.wb.reset(in, out)
e.resetCommon()
}
// Encode writes an object into a stream.
//
// Encoding can be configured via the struct tag for the fields.
// The key (in the struct tags) that we look at is configurable.
//
// By default, we look up the "codec" key in the struct field's tags,
// and fall bak to the "json" key if "codec" is absent.
// That key in struct field's tag value is the key name,
// followed by an optional comma and options.
//
// To set an option on all fields (e.g. omitempty on all fields), you
// can create a field called _struct, and set flags on it. The options
// which can be set on _struct are:
// - omitempty: so all fields are omitted if empty
// - toarray: so struct is encoded as an array
// - int: so struct key names are encoded as signed integers (instead of strings)
// - uint: so struct key names are encoded as unsigned integers (instead of strings)
// - float: so struct key names are encoded as floats (instead of strings)
// More details on these below.
//
// Struct values "usually" encode as maps. Each exported struct field is encoded unless:
// - the field's tag is "-", OR
// - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
//
// When encoding as a map, the first string in the tag (before the comma)
// is the map key string to use when encoding.
// ...
// This key is typically encoded as a string.
// However, there are instances where the encoded stream has mapping keys encoded as numbers.
// For example, some cbor streams have keys as integer codes in the stream, but they should map
// to fields in a structured object. Consequently, a struct is the natural representation in code.
// For these, configure the struct to encode/decode the keys as numbers (instead of string).
// This is done with the int,uint or float option on the _struct field (see above).
//
// However, struct values may encode as arrays. This happens when:
// - StructToArray Encode option is set, OR
// - the tag on the _struct field sets the "toarray" option
// Note that omitempty is ignored when encoding struct values as arrays,
// as an entry must be encoded for each field, to maintain its position.
//
// Values with types that implement MapBySlice are encoded as stream maps.
//
// The empty values (for omitempty option) are false, 0, any nil pointer
// or interface value, and any array, slice, map, or string of length zero.
//
// Anonymous fields are encoded inline except:
// - the struct tag specifies a replacement name (first value)
// - the field is of an interface type
//
// Examples:
//
// // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
// type MyStruct struct {
// _struct bool `codec:",omitempty"` //set omitempty for every field
// Field1 string `codec:"-"` //skip this field
// Field2 int `codec:"myName"` //Use key "myName" in encode stream
// Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
// Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
// io.Reader //use key "Reader".
// MyStruct `codec:"my1" //use key "my1".
// MyStruct //inline it
// ...
// }
//
// type MyStruct struct {
// _struct bool `codec:",toarray"` //encode struct as an array
// }
//
// type MyStruct struct {
// _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys
// Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1)
// Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2)
// }
//
// The mode of encoding is based on the type of the value. When a value is seen:
// - If a Selfer, call its CodecEncodeSelf method
// - If an extension is registered for it, call that extension function
// - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method
// - Else encode it based on its reflect.Kind
//
// Note that struct field names and keys in map[string]XXX will be treated as symbols.
// Some formats support symbols (e.g. binc) and will properly encode the string
// only once in the stream, and use a tag to refer to it thereafter.
func (e *Encoder) Encode(v interface{}) (err error) {
// tried to use closure, as runtime optimizes defer with no params.
// This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
// Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
// defer func() { e.deferred(&err) }() }
// { x, y := e, &err; defer func() { x.deferred(y) }() }
if e.err != nil {
return e.err
}
if recoverPanicToErr {
defer func() {
// if error occurred during encoding, return that error;
// else if error occurred on end'ing (i.e. during flush), return that error.
err = e.w().endErr()
x := recover()
if x == nil {
if e.err != err {
e.err = err
}
} else {
panicValToErr(e, x, &e.err)
if e.err != err {
err = e.err
}
}
}()
}
// defer e.deferred(&err)
e.mustEncode(v)
return
}
// MustEncode is like Encode, but panics if unable to Encode.
// This provides insight to the code location that triggered the error.
func (e *Encoder) MustEncode(v interface{}) {
if e.err != nil {
panic(e.err)
}
e.mustEncode(v)
}
func (e *Encoder) mustEncode(v interface{}) {
e.calls++
e.encode(v)
e.calls--
if e.calls == 0 {
e.e.atEndOfEncode()
e.w().end()
}
}
// Release releases shared (pooled) resources.
//
// It is important to call Release() when done with an Encoder, so those resources
// are released instantly for use by subsequently created Encoders.
//
// Deprecated: Release is a no-op as pooled resources are not used with an Encoder.
// This method is kept for compatibility reasons only.
func (e *Encoder) Release() {
}
func (e *Encoder) encode(iv interface{}) {
// a switch with only concrete types can be optimized.
// consequently, we deal with nil and interfaces outside the switch.
if iv == nil {
e.e.EncodeNil()
return
}
rv, ok := isNil(iv)
if ok {
e.e.EncodeNil()
return
}
var vself Selfer
switch v := iv.(type) {
// case nil:
// case Selfer:
case Raw:
e.rawBytes(v)
case reflect.Value:
e.encodeValue(v, nil)
case string:
e.e.EncodeString(v)
case bool:
e.e.EncodeBool(v)
case int:
e.e.EncodeInt(int64(v))
case int8:
e.e.EncodeInt(int64(v))
case int16:
e.e.EncodeInt(int64(v))
case int32:
e.e.EncodeInt(int64(v))
case int64:
e.e.EncodeInt(v)
case uint:
e.e.EncodeUint(uint64(v))
case uint8:
e.e.EncodeUint(uint64(v))
case uint16:
e.e.EncodeUint(uint64(v))
case uint32:
e.e.EncodeUint(uint64(v))
case uint64:
e.e.EncodeUint(v)
case uintptr:
e.e.EncodeUint(uint64(v))
case float32:
e.e.EncodeFloat32(v)
case float64:
e.e.EncodeFloat64(v)
case time.Time:
e.e.EncodeTime(v)
case []uint8:
e.e.EncodeStringBytesRaw(v)
case *Raw:
e.rawBytes(*v)
case *string:
e.e.EncodeString(*v)
case *bool:
e.e.EncodeBool(*v)
case *int:
e.e.EncodeInt(int64(*v))
case *int8:
e.e.EncodeInt(int64(*v))
case *int16:
e.e.EncodeInt(int64(*v))
case *int32:
e.e.EncodeInt(int64(*v))
case *int64:
e.e.EncodeInt(*v)
case *uint:
e.e.EncodeUint(uint64(*v))
case *uint8:
e.e.EncodeUint(uint64(*v))
case *uint16:
e.e.EncodeUint(uint64(*v))
case *uint32:
e.e.EncodeUint(uint64(*v))
case *uint64:
e.e.EncodeUint(*v)
case *uintptr:
e.e.EncodeUint(uint64(*v))
case *float32:
e.e.EncodeFloat32(*v)
case *float64:
e.e.EncodeFloat64(*v)
case *time.Time:
e.e.EncodeTime(*v)
case *[]uint8:
if *v == nil {
e.e.EncodeNil()
} else {
e.e.EncodeStringBytesRaw(*v)
}
default:
if vself, ok = iv.(Selfer); ok {
vself.CodecEncodeSelf(e)
} else if !fastpathEncodeTypeSwitch(iv, e) {
if !rv.IsValid() {
rv = rv4i(iv)
}
e.encodeValue(rv, nil)
}
}
}
func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn) {
// if a valid fn is passed, it MUST BE for the dereferenced type of rv
// We considered using a uintptr (a pointer) 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.
var sptr interface{} // uintptr
var rvp reflect.Value
var rvpValid bool
TOP:
switch rv.Kind() {
case reflect.Ptr:
if rvIsNil(rv) {
e.e.EncodeNil()
return
}
rvpValid = true
rvp = rv
rv = rv.Elem()
if e.h.CheckCircularRef && rv.Kind() == reflect.Struct {
sptr = rv2i(rvp) // rv.UnsafeAddr()
break TOP
}
goto TOP
case reflect.Interface:
if rvIsNil(rv) {
e.e.EncodeNil()
return
}
rv = rv.Elem()
goto TOP
case reflect.Slice, reflect.Map:
if rvIsNil(rv) {
e.e.EncodeNil()
return
}
case reflect.Invalid, reflect.Func:
e.e.EncodeNil()
return
}
if sptr != nil && (&e.ci).add(sptr) {
e.errorf("circular reference found: # %p, %T", sptr, sptr)
}
var rt reflect.Type
if fn == nil {
rt = rv.Type()
fn = e.h.fn(rt)
}
if fn.i.addrE {
if rvpValid {
fn.fe(e, &fn.i, rvp)
} else if rv.CanAddr() {
fn.fe(e, &fn.i, rv.Addr())
} else {
if rt == nil {
rt = rv.Type()
}
rv2 := reflect.New(rt)
rvSetDirect(rv2.Elem(), rv)
fn.fe(e, &fn.i, rv2)
}
} else {
fn.fe(e, &fn.i, rv)
}
if sptr != 0 {
(&e.ci).remove(sptr)
}
}
func (e *Encoder) marshalUtf8(bs []byte, fnerr error) {
if fnerr != nil {
panic(fnerr)
}
if bs == nil {
e.e.EncodeNil()
} else {
e.e.EncodeString(stringView(bs))
// e.e.EncodeStringEnc(cUTF8, stringView(bs))
}
}
func (e *Encoder) marshalAsis(bs []byte, fnerr error) {
if fnerr != nil {
panic(fnerr)
}
if bs == nil {
e.e.EncodeNil()
} else {
e.encWr.writeb(bs) // e.asis(bs)
}
}
func (e *Encoder) marshalRaw(bs []byte, fnerr error) {
if fnerr != nil {
panic(fnerr)
}
if bs == nil {
e.e.EncodeNil()
} else {
e.e.EncodeStringBytesRaw(bs)
}
}
func (e *Encoder) rawBytes(vv Raw) {
v := []byte(vv)
if !e.h.Raw {
e.errorf("Raw values cannot be encoded: %v", v)
}
e.encWr.writeb(v) // e.asis(v)
}
func (e *Encoder) wrapErr(v interface{}, err *error) {
*err = encodeError{codecError{name: e.hh.Name(), err: v}}
}
// ---- container tracker methods
// Note: We update the .c after calling the callback.
// This way, the callback can know what the last status was.
func (e *Encoder) mapStart(length int) {
e.e.WriteMapStart(length)
e.c = containerMapStart
}
func (e *Encoder) mapElemKey() {
if e.js {
e.jsondriver().WriteMapElemKey()
}
e.c = containerMapKey
}
func (e *Encoder) mapElemValue() {
if e.js {
e.jsondriver().WriteMapElemValue()
}
e.c = containerMapValue
}
func (e *Encoder) mapEnd() {
e.e.WriteMapEnd()
// e.c = containerMapEnd
e.c = 0
}
func (e *Encoder) arrayStart(length int) {
e.e.WriteArrayStart(length)
e.c = containerArrayStart
}
func (e *Encoder) arrayElem() {
if e.js {
e.jsondriver().WriteArrayElem()
}
e.c = containerArrayElem
}
func (e *Encoder) arrayEnd() {
e.e.WriteArrayEnd()
e.c = 0
// e.c = containerArrayEnd
}
// ----------
func (e *Encoder) sideEncode(v interface{}, bs *[]byte) {
rv := baseRV(v)
e2 := NewEncoderBytes(bs, e.hh)
e2.encodeValue(rv, e.h.fnNoExt(rv.Type()))
e2.e.atEndOfEncode()
e2.w().end()
}
func encStructFieldKey(encName string, ee encDriver, w *encWr,
keyType valueType, encNameAsciiAlphaNum bool, js bool) {
var m must
// use if-else-if, not switch (which compiles to binary-search)
// since keyType is typically valueTypeString, branch prediction is pretty good.
if keyType == valueTypeString {
if js && encNameAsciiAlphaNum { // keyType == valueTypeString
w.writeqstr(encName)
} else { // keyType == valueTypeString
ee.EncodeString(encName)
}
} else if keyType == valueTypeInt {
ee.EncodeInt(m.Int(strconv.ParseInt(encName, 10, 64)))
} else if keyType == valueTypeUint {
ee.EncodeUint(m.Uint(strconv.ParseUint(encName, 10, 64)))
} else if keyType == valueTypeFloat {
ee.EncodeFloat64(m.Float(strconv.ParseFloat(encName, 64)))
}
}