-
Notifications
You must be signed in to change notification settings - Fork 23
/
binary.go
1257 lines (1161 loc) · 31.8 KB
/
binary.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
package binary
import (
"encoding/binary"
"errors"
"io"
"math"
"sync"
"unicode/utf8"
"unsafe"
"github.com/cloudwego/dynamicgo/internal/primitive"
"github.com/cloudwego/dynamicgo/internal/rt"
"github.com/cloudwego/dynamicgo/meta"
"github.com/cloudwego/dynamicgo/proto"
"github.com/cloudwego/dynamicgo/proto/protowire"
)
// memory resize factor
const (
defaultBufferSize = 4096
growBufferFactor = 1
defaultListSize = 5
speculativeLength = 1 // prefixed bytes length when write complex fields
)
var (
errDismatchPrimitive = meta.NewError(meta.ErrDismatchType, "dismatch primitive types", nil)
errInvalidDataSize = meta.NewError(meta.ErrInvalidParam, "invalid data size", nil) // not used
errInvalidTag = meta.NewError(meta.ErrInvalidParam, "invalid tag in ReadMessageBegin", nil)
errInvalidFieldNumber = meta.NewError(meta.ErrInvalidParam, "invalid field number", nil)
errExceedDepthLimit = meta.NewError(meta.ErrStackOverflow, "exceed depth limit", nil) // not used
errInvalidDataType = meta.NewError(meta.ErrRead, "invalid data type", nil)
errUnknonwField = meta.NewError(meta.ErrUnknownField, "unknown field", nil)
errUnsupportedType = meta.NewError(meta.ErrUnsupportedType, "unsupported type", nil)
errNotImplemented = meta.NewError(meta.ErrNotImplemented, "not implemted type", nil) // not used
ErrConvert = meta.NewError(meta.ErrConvert, "convert type error", nil)
errDecodeField = meta.NewError(meta.ErrRead, "invalid field data", nil)
)
// We append to an empty array rather than a nil []byte to get non-nil zero-length byte slices.
var emptyBuf [0]byte
// Serizalize data to byte array and reuse the memory
type BinaryProtocol struct {
Buf []byte
Read int
}
var (
bpPool = sync.Pool{
New: func() interface{} {
return &BinaryProtocol{
Buf: make([]byte, 0, defaultBufferSize),
}
},
}
)
func (p *BinaryProtocol) malloc(size int) ([]byte, error) {
if size <= 0 {
panic(errors.New("invalid size"))
}
l := len(p.Buf)
c := cap(p.Buf)
d := l + size
if d > c {
c += c >> growBufferFactor
if d > c {
c = d * 2
}
buf := rt.Growslice(byteType, *(*rt.GoSlice)(unsafe.Pointer(&p.Buf)), c)
p.Buf = *(*[]byte)(unsafe.Pointer(&buf))
}
p.Buf = (p.Buf)[:d]
return (p.Buf)[l:d], nil
}
// next ...
func (p *BinaryProtocol) next(size int) ([]byte, error) {
if size <= 0 {
panic(errors.New("invalid size"))
}
l := len(p.Buf)
d := p.Read + size
if d > l {
return nil, io.EOF
}
ret := (p.Buf)[p.Read:d]
p.Read = d
return ret, nil
}
// Reset resets the buffer and read position
func (p *BinaryProtocol) Reset() {
p.Read = 0
p.Buf = p.Buf[:0]
}
// RawBuf returns the raw buffer of the protocol
func (p *BinaryProtocol) RawBuf() []byte {
return p.Buf
}
// Left returns the left bytes to read
func (p *BinaryProtocol) Left() int {
return len(p.Buf) - p.Read
}
// BinaryProtocol Method
func NewBinaryProtol(buf []byte) *BinaryProtocol {
bp := bpPool.Get().(*BinaryProtocol)
bp.Buf = buf
return bp
}
func NewBinaryProtocolBuffer() *BinaryProtocol {
bp := bpPool.Get().(*BinaryProtocol)
return bp
}
func FreeBinaryProtocol(bp *BinaryProtocol) {
bp.Reset()
bpPool.Put(bp)
}
func (p *BinaryProtocol) Recycle() {
p.Reset()
bpPool.Put(p)
}
// Append Tag
func (p *BinaryProtocol) AppendTag(num proto.FieldNumber, typ proto.WireType) error {
tag := uint64(num)<<3 | uint64(typ&7)
if num > proto.MaxValidNumber || num < proto.MinValidNumber {
return errInvalidFieldNumber
}
p.Buf = protowire.BinaryEncoder{}.EncodeUint64(p.Buf, tag)
return nil
}
// Append Tag With FieldDescriptor by kind, you must use kind to write tag, because the typedesc when list has no tag
func (p *BinaryProtocol) AppendTagByKind(number proto.FieldNumber, kind proto.ProtoKind) error {
return p.AppendTag(number, proto.Kind2Wire[kind])
}
// ConsumeTag parses b as a varint-encoded tag, reporting its length.
func (p *BinaryProtocol) ConsumeTag() (proto.FieldNumber, proto.WireType, int, error) {
v, n := protowire.ConsumeVarint((p.Buf)[p.Read:])
if n < 0 {
return 0, 0, n, errInvalidTag
}
_, err := p.next(n)
if v>>3 > uint64(math.MaxInt32) {
return -1, 0, n, errUnknonwField
}
num, typ := proto.FieldNumber(v>>3), proto.WireType(v&7)
if num < proto.MinValidNumber {
return 0, 0, n, errInvalidFieldNumber
}
return num, typ, n, err
}
// ConsumeChildTag parses b as a varint-encoded tag, don't move p.Read
func (p *BinaryProtocol) ConsumeTagWithoutMove() (proto.FieldNumber, proto.WireType, int, error) {
v, n := protowire.ConsumeVarint((p.Buf)[p.Read:])
if n < 0 {
return 0, 0, n, errInvalidTag
}
if v>>3 > uint64(math.MaxInt32) {
return -1, 0, n, errUnknonwField
}
num, typ := proto.FieldNumber(v>>3), proto.WireType(v&7)
if num < proto.MinValidNumber {
return 0, 0, n, errInvalidFieldNumber
}
return num, typ, n, nil
}
// When encoding length-prefixed fields, we speculatively set aside some number of bytes
// for the length, encode the data, and then encode the length (shifting the data if necessary
// to make room).
func AppendSpeculativeLength(b []byte) ([]byte, int) {
pos := len(b)
b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...) // the max length is 4
return b, pos
}
func FinishSpeculativeLength(b []byte, pos int) []byte {
mlen := len(b) - pos - speculativeLength
msiz := protowire.SizeVarint(uint64(mlen))
if msiz != speculativeLength {
if cap(b) >= pos+msiz+mlen {
b = b[:pos+msiz+mlen]
} else {
newSlice := make([]byte, pos+msiz+mlen)
copy(newSlice, b)
b = newSlice
}
copy(b[pos+msiz:], b[pos+speculativeLength:])
}
protowire.AppendVarint(b[:pos], uint64(mlen))
return b
}
/**
* Write methods
*/
// WriteBool
func (p *BinaryProtocol) WriteBool(value bool) error {
if value {
return p.WriteUint64(uint64(1))
} else {
return p.WriteUint64(uint64(0))
}
}
// WriteInt32
func (p *BinaryProtocol) WriteInt32(value int32) error {
p.Buf = protowire.BinaryEncoder{}.EncodeInt32(p.Buf, value)
return nil
}
// WriteSint32
func (p *BinaryProtocol) WriteSint32(value int32) error {
p.Buf = protowire.BinaryEncoder{}.EncodeSint32(p.Buf, value)
return nil
}
// WriteUint32
func (p *BinaryProtocol) WriteUint32(value uint32) error {
p.Buf = protowire.BinaryEncoder{}.EncodeUint32(p.Buf, value)
return nil
}
// Writefixed32
func (p *BinaryProtocol) WriteFixed32(value int32) error {
v, err := p.malloc(4)
if err != nil {
return err
}
binary.LittleEndian.PutUint32(v, uint32(value))
return err
}
// WriteSfixed32
func (p *BinaryProtocol) WriteSfixed32(value int32) error {
v, err := p.malloc(4)
if err != nil {
return err
}
binary.LittleEndian.PutUint32(v, uint32(value))
return err
}
// WriteInt64
func (p *BinaryProtocol) WriteInt64(value int64) error {
p.Buf = protowire.BinaryEncoder{}.EncodeInt64(p.Buf, value)
return nil
}
// WriteSint64
func (p *BinaryProtocol) WriteSint64(value int64) error {
p.Buf = protowire.BinaryEncoder{}.EncodeSint64(p.Buf, value)
return nil
}
// WriteUint64
func (p *BinaryProtocol) WriteUint64(value uint64) error {
p.Buf = protowire.BinaryEncoder{}.EncodeUint64(p.Buf, value)
return nil
}
// Writefixed64
func (p *BinaryProtocol) WriteFixed64(value uint64) error {
v, err := p.malloc(8)
if err != nil {
return err
}
binary.LittleEndian.PutUint64(v, value)
return err
}
// WriteSfixed64
func (p *BinaryProtocol) WriteSfixed64(value int64) error {
v, err := p.malloc(8)
if err != nil {
return err
}
binary.LittleEndian.PutUint64(v, uint64(value))
return err
}
// WriteFloat
func (p *BinaryProtocol) WriteFloat(value float32) error {
v, err := p.malloc(4)
if err != nil {
return err
}
binary.LittleEndian.PutUint32(v, math.Float32bits(float32(value)))
return err
}
// WriteDouble
func (p *BinaryProtocol) WriteDouble(value float64) error {
v, err := p.malloc(8)
if err != nil {
return err
}
binary.LittleEndian.PutUint64(v, math.Float64bits(value))
return err
}
// WriteString
func (p *BinaryProtocol) WriteString(value string) error {
if !utf8.ValidString(value) {
return meta.NewError(meta.ErrInvalidParam, value, nil)
}
p.Buf = protowire.BinaryEncoder{}.EncodeString(p.Buf, value)
return nil
}
// WriteBytes
func (p *BinaryProtocol) WriteBytes(value []byte) error {
p.Buf = protowire.BinaryEncoder{}.EncodeBytes(p.Buf, value)
return nil
}
// WriteEnum
func (p *BinaryProtocol) WriteEnum(value proto.EnumNumber) error {
p.Buf = protowire.BinaryEncoder{}.EncodeInt64(p.Buf, int64(value))
return nil
}
/*
* WriteList
* packed format:[tag][length][value value value value....]
* unpacked format:[tag][(length)][value][tag][(length)][value][tag][(length)][value]....
* accpet val type: []interface{}
*/
func (p *BinaryProtocol) WriteList(desc *proto.TypeDescriptor, val interface{}, cast bool, disallowUnknown bool, useFieldName bool) error {
vs, ok := val.([]interface{})
if !ok {
return errDismatchPrimitive
}
fieldId := desc.BaseId()
NeedMessageLen := true
// packed List bytes format: [tag][length][(L)V][value][value]...
if desc.IsPacked() && len(vs) > 0 {
p.AppendTag(fieldId, proto.BytesType)
var pos int
p.Buf, pos = AppendSpeculativeLength(p.Buf)
for _, v := range vs {
if err := p.WriteBaseTypeWithDesc(desc.Elem(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil {
return err
}
}
p.Buf = FinishSpeculativeLength(p.Buf, pos)
return nil
}
// unpacked List bytes format: [T(L)V][T(L)V]...
for _, v := range vs {
// share the same field number for Tag
if err := p.AppendTag(fieldId, proto.BytesType); err != nil {
return err
}
if err := p.WriteBaseTypeWithDesc(desc.Elem(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil {
return err
}
}
return nil
}
/*
* WriteMap
* Map bytes format: [Pairtag][Pairlength][keyTag(L)V][valueTag(L)V] [Pairtag][Pairlength][T(L)V][T(L)V]...
* Pairtag = MapFieldnumber << 3 | wiretype, wiertype = proto.BytesType
* accpet val type: map[string]interface{} or map[int]interface{} or map[interface{}]interface{}
*/
func (p *BinaryProtocol) WriteMap(desc *proto.TypeDescriptor, val interface{}, cast bool, disallowUnknown bool, useFieldName bool) error {
baseId := desc.BaseId()
MapKey := desc.Key()
MapValue := desc.Elem()
// check val is map[string]interface{} or map[int]interface{} or map[interface{}]interface{}
var vs map[string]interface{}
var vs2 map[int]interface{}
var vs3 map[interface{}]interface{}
var ok bool
if vs, ok = val.(map[string]interface{}); !ok {
if vs2, ok = val.(map[int]interface{}); !ok {
if vs3, ok = val.(map[interface{}]interface{}); !ok {
return errDismatchPrimitive
}
}
}
NeedMessageLen := true
if vs != nil {
for k, v := range vs {
p.AppendTag(baseId, proto.BytesType)
var pos int
p.Buf, pos = AppendSpeculativeLength(p.Buf)
p.AppendTag(1, MapKey.WireType())
p.WriteString(k)
p.AppendTag(2, MapValue.WireType())
p.WriteBaseTypeWithDesc(MapValue, v, cast, NeedMessageLen, disallowUnknown, useFieldName)
p.Buf = FinishSpeculativeLength(p.Buf, pos)
}
} else if vs2 != nil {
for k, v := range vs2 {
p.AppendTag(baseId, proto.BytesType)
var pos int
p.Buf, pos = AppendSpeculativeLength(p.Buf)
p.AppendTag(1, MapKey.WireType())
// notice: may have problem, when k is sfixed64/fixed64 or sfixed32/fixed32 there is no need to use varint
// we had better add more code to judge the type of k if write fast
// p.WriteInt64(int64(k))
p.WriteBaseTypeWithDesc(MapKey, k, NeedMessageLen, cast, disallowUnknown, useFieldName) // the gerneral way
p.AppendTag(2, MapValue.WireType())
p.WriteBaseTypeWithDesc(MapValue, v, NeedMessageLen, cast, disallowUnknown, useFieldName)
p.Buf = FinishSpeculativeLength(p.Buf, pos)
}
} else {
for k, v := range vs3 {
p.AppendTag(baseId, proto.BytesType)
var pos int
p.Buf, pos = AppendSpeculativeLength(p.Buf)
p.AppendTag(1, MapKey.WireType())
p.WriteBaseTypeWithDesc(MapKey, k, NeedMessageLen, cast, disallowUnknown, useFieldName) // the gerneral way
p.AppendTag(2, MapValue.WireType())
p.WriteBaseTypeWithDesc(MapValue, v, NeedMessageLen, cast, disallowUnknown, useFieldName)
p.Buf = FinishSpeculativeLength(p.Buf, pos)
}
}
return nil
}
/*
* Write Message
* accpet val type: map[string]interface{} or map[proto.FieldNumber]interface{}
* message fields format: [fieldTag(L)V][fieldTag(L)V]...
*/
func (p *BinaryProtocol) WriteMessageFields(desc *proto.MessageDescriptor, val interface{}, cast bool, disallowUnknown bool, useFieldName bool) error {
NeedMessageLen := true
if useFieldName {
for name, v := range val.(map[string]interface{}) {
f := desc.ByName(name)
if f == nil {
if disallowUnknown {
return errUnknonwField
}
// unknown field will skip when writing
continue
}
if !f.IsMap() && !f.IsList() {
if err := p.AppendTag(f.Number(), proto.Kind2Wire[f.Kind()]); err != nil {
return meta.NewError(meta.ErrWrite, "append field tag failed", nil)
}
}
if err := p.WriteAnyWithDesc(f.Type(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil {
return err
}
}
} else {
for fieldNumber, v := range val.(map[proto.FieldNumber]interface{}) {
f := desc.ByNumber(fieldNumber)
if f == nil {
if disallowUnknown {
return errUnknonwField
}
continue
}
if !f.IsMap() && !f.IsList() {
if err := p.AppendTag(f.Number(), proto.Kind2Wire[f.Kind()]); err != nil {
return meta.NewError(meta.ErrWrite, "append field tag failed", nil)
}
}
if err := p.WriteAnyWithDesc(f.Type(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil {
return err
}
}
}
return nil
}
// WriteBaseType Fields with FieldDescriptor format: (L)V
func (p *BinaryProtocol) WriteBaseTypeWithDesc(desc *proto.TypeDescriptor, val interface{}, NeedMessageLen bool, cast bool, disallowUnknown bool, useFieldName bool) error {
switch desc.Type() {
case proto.BOOL:
v, ok := val.(bool)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
v, err = primitive.ToBool(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteBool(v)
case proto.ENUM:
v, ok := val.(proto.EnumNumber)
if !ok {
return meta.NewError(meta.ErrConvert, "convert enum error", nil)
}
p.WriteEnum(v)
case proto.INT32:
v, ok := val.(int32)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
vv, err := primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
v = int32(vv)
}
}
p.WriteInt32(v)
case proto.SINT32:
v, ok := val.(int32)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
vv, err := primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
v = int32(vv)
}
}
p.WriteSint32(v)
case proto.UINT32:
v, ok := val.(uint32)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
vv, err := primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
v = uint32(vv)
}
}
p.WriteUint32(v)
case proto.INT64:
v, ok := val.(int64)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
v, err = primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteInt64(v)
case proto.SINT64:
v, ok := val.(int64)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
v, err = primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteSint64(v)
case proto.UINT64:
v, ok := val.(uint64)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
vv, err := primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
v = uint64(vv)
}
}
p.WriteUint64(v)
case proto.SFIX32:
v, ok := val.(int32)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
vv, err := primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
v = int32(vv)
}
}
p.WriteSfixed32(v)
case proto.FIX32:
v, ok := val.(int32)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
vv, err := primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
v = int32(vv)
}
}
p.WriteFixed32(v)
case proto.FLOAT:
v, ok := val.(float32)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
vfloat64, err := primitive.ToFloat64(val)
v = float32(vfloat64)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteFloat(v)
case proto.SFIX64:
v, ok := val.(int64)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
v, err = primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteSfixed64(v)
case proto.FIX64:
v, ok := val.(int64)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
v, err = primitive.ToInt64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteSfixed64(v)
case proto.DOUBLE:
v, ok := val.(float64)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
v, err = primitive.ToFloat64(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteDouble(v)
case proto.STRING:
v, ok := val.(string)
if !ok {
if !cast {
return errDismatchPrimitive
} else {
var err error
v, err = primitive.ToString(val)
if err != nil {
return meta.NewError(meta.ErrConvert, "", err)
}
}
}
p.WriteString(v)
case proto.BYTE:
v, ok := val.([]byte)
if !ok {
return meta.NewError(meta.ErrConvert, "write bytes kind error", nil)
}
p.WriteBytes(v)
case proto.MESSAGE:
var ok bool
var pos int
// prefix message length
if NeedMessageLen {
p.Buf, pos = AppendSpeculativeLength(p.Buf)
}
if useFieldName {
val, ok = val.(map[string]interface{})
} else {
val, ok = val.(map[proto.FieldNumber]interface{})
}
if !ok {
return errDismatchPrimitive
}
msg := desc.Message()
if err := p.WriteMessageFields(msg, val, cast, disallowUnknown, useFieldName); err != nil {
return err
}
// write message length
if NeedMessageLen {
p.Buf = FinishSpeculativeLength(p.Buf, pos)
}
default:
return errUnsupportedType
}
return nil
}
// WriteAnyWithDesc explain desc and val and write them into buffer
// - LIST will be converted from []interface{}
// - MAP will be converted from map[string]interface{} or map[int]interface{} or map[interface{}]interface{}
// - MESSAGE will be converted from map[FieldNumber]interface{} or map[string]interface{}
func (p *BinaryProtocol) WriteAnyWithDesc(desc *proto.TypeDescriptor, val interface{}, NeedMessageLen bool, cast bool, disallowUnknown bool, useFieldName bool) error {
switch {
case desc.IsList():
return p.WriteList(desc, val, cast, disallowUnknown, useFieldName)
case desc.IsMap():
return p.WriteMap(desc, val, cast, disallowUnknown, useFieldName)
default:
return p.WriteBaseTypeWithDesc(desc, val, NeedMessageLen, cast, disallowUnknown, useFieldName)
}
}
/**
* Read methods
*/
// ReadByte
func (p *BinaryProtocol) ReadByte() (value byte, err error) {
buf, err := p.next(1)
if err != nil {
return value, err
}
return byte(buf[0]), err
}
// ReadBool
func (p *BinaryProtocol) ReadBool() (bool, error) {
v, n := protowire.BinaryDecoder{}.DecodeBool((p.Buf)[p.Read:])
if n < 0 {
return false, errDecodeField
}
_, err := p.next(n)
return v, err
}
// ReadInt containing INT32, SINT32, SFIX32, INT64, SINT64, SFIX64, UINT32, UINT64
func (p *BinaryProtocol) ReadInt(t proto.Type) (value int, err error) {
switch t {
case proto.INT32:
n, err := p.ReadInt32()
return int(n), err
case proto.SINT32:
n, err := p.ReadSint32()
return int(n), err
case proto.SFIX32:
n, err := p.ReadSfixed32()
return int(n), err
case proto.INT64:
n, err := p.ReadInt64()
return int(n), err
case proto.SINT64:
n, err := p.ReadSint64()
return int(n), err
case proto.SFIX64:
n, err := p.ReadSfixed64()
return int(n), err
case proto.UINT32:
n, err := p.ReadUint32()
return int(n), err
case proto.UINT64:
n, err := p.ReadUint64()
return int(n), err
default:
return 0, errInvalidDataType
}
}
// ReadI32
func (p *BinaryProtocol) ReadInt32() (int32, error) {
value, n := protowire.BinaryDecoder{}.DecodeInt32((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadSint32
func (p *BinaryProtocol) ReadSint32() (int32, error) {
value, n := protowire.BinaryDecoder{}.DecodeSint32((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadUint32
func (p *BinaryProtocol) ReadUint32() (uint32, error) {
value, n := protowire.BinaryDecoder{}.DecodeUint32((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadI64
func (p *BinaryProtocol) ReadInt64() (int64, error) {
value, n := protowire.BinaryDecoder{}.DecodeInt64((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadSint64
func (p *BinaryProtocol) ReadSint64() (int64, error) {
value, n := protowire.BinaryDecoder{}.DecodeSint64((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadUint64
func (p *BinaryProtocol) ReadUint64() (uint64, error) {
value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadVarint
func (p *BinaryProtocol) ReadVarint() (uint64, error) {
value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadFixed32
func (p *BinaryProtocol) ReadFixed32() (int32, error) {
value, n := protowire.BinaryDecoder{}.DecodeFixed32((p.Buf)[p.Read:])
if n < 0 {
return int32(value), errDecodeField
}
_, err := p.next(n)
return int32(value), err
}
// ReadSFixed32
func (p *BinaryProtocol) ReadSfixed32() (int32, error) {
value, n := protowire.BinaryDecoder{}.DecodeFixed32((p.Buf)[p.Read:])
if n < 0 {
return int32(value), errDecodeField
}
_, err := p.next(n)
return int32(value), err
}
// ReadFloat
func (p *BinaryProtocol) ReadFloat() (float32, error) {
value, n := protowire.BinaryDecoder{}.DecodeFloat32((p.Buf)[p.Read:])
if n < 0 {
return value, errDecodeField
}
_, err := p.next(n)
return value, err
}
// ReadFixed64
func (p *BinaryProtocol) ReadFixed64() (int64, error) {
value, n := protowire.BinaryDecoder{}.DecodeFixed64((p.Buf)[p.Read:])
if n < 0 {
return int64(value), errDecodeField
}
_, err := p.next(n)
return int64(value), err
}
// ReadSFixed64
func (p *BinaryProtocol) ReadSfixed64() (int64, error) {
value, n := protowire.BinaryDecoder{}.DecodeFixed64((p.Buf)[p.Read:])
if n < 0 {
return int64(value), errDecodeField
}
_, err := p.next(n)
return int64(value), err
}
// ReadDouble
func (p *BinaryProtocol) ReadDouble() (float64, error) {
value, n := protowire.BinaryDecoder{}.DecodeFixed64((p.Buf)[p.Read:])
if n < 0 {
return math.Float64frombits(value), errDecodeField
}
_, err := p.next(n)
return math.Float64frombits(value), err
}
// ReadBytes return bytesData and the sum length of L、V in TLV
func (p *BinaryProtocol) ReadBytes() ([]byte, error) {
value, n, all := protowire.BinaryDecoder{}.DecodeBytes((p.Buf)[p.Read:])
if n < 0 {
return emptyBuf[:], errDecodeField
}
_, err := p.next(all)
return value, err
}
// ReadLength return dataLength, and move pointer in the begin of data
func (p *BinaryProtocol) ReadLength() (int, error) {
value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:])
if n < 0 {
return 0, errDecodeField
}
_, err := p.next(n)
return int(value), err
}
// ReadString
func (p *BinaryProtocol) ReadString(copy bool) (value string, err error) {
bytes, n, all := protowire.BinaryDecoder{}.DecodeBytes((p.Buf)[p.Read:])
if n < 0 {
return "", errDecodeField
}
if copy {
value = string(bytes)
} else {
v := (*rt.GoString)(unsafe.Pointer(&value))
v.Ptr = rt.IndexPtr(*(*unsafe.Pointer)(unsafe.Pointer(&p.Buf)), byteTypeSize, p.Read+n)
v.Len = int(all - n)
}
_, err = p.next(all)
return
}
// ReadEnum
func (p *BinaryProtocol) ReadEnum() (proto.EnumNumber, error) {
value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:])
if n < 0 {
return 0, errDecodeField
}
_, err := p.next(n)
return proto.EnumNumber(value), err
}
// ReadList
func (p *BinaryProtocol) ReadList(desc *proto.TypeDescriptor, copyString bool, disallowUnknown bool, useFieldName bool) ([]interface{}, error) {
hasMessageLen := true
elemetdesc := desc.Elem()
// Read ListTag
fieldNumber, _, _, listTagErr := p.ConsumeTag()
if listTagErr != nil {
return nil, meta.NewError(meta.ErrRead, "ConsumeTag failed", nil)