-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdecoder.go
698 lines (626 loc) · 16.5 KB
/
decoder.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
package binary
import (
"fmt"
"io"
"math"
"reflect"
)
// NewDecoder make a new Decoder object with buffer.
func NewDecoder(buffer []byte) *Decoder {
return NewDecoderEndian(buffer, DefaultEndian)
}
// NewDecoderEndian make a new Decoder object with buffer and endian.
func NewDecoderEndian(buffer []byte, endian Endian) *Decoder {
p := &Decoder{}
p.Init(buffer, endian)
return p
}
// Decoder is used to decode byte array to go data.
type Decoder struct {
coder
reader io.Reader //for decode from reader only
boolValue byte //last bool value byte
}
// Skip ignore the next size of bytes for encoding/decoding.
// It will panic If space not enough.
// It will return -1 if size <= 0.
func (decoder *Decoder) Skip(size int) int {
if nil == decoder.reserve(size) {
return -1
}
return size
}
// reserve returns next size bytes for encoding/decoding.
func (decoder *Decoder) reserve(size int) []byte {
if decoder.reader != nil { //decode from reader
if size > len(decoder.buff) {
decoder.buff = make([]byte, size)
}
buff := decoder.buff[:size]
if n, _ := decoder.reader.Read(buff); n < size {
panic(io.ErrUnexpectedEOF)
}
return buff
}
return decoder.coder.reserve(size) //decode from bytes buffer
}
// Init initialize Encoder with buffer and endian.
func (decoder *Decoder) Init(buffer []byte, endian Endian) {
decoder.buff = buffer
decoder.pos = 0
decoder.endian = endian
}
// Bool decode a bool value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Bool() bool {
if decoder.boolBit == 0 {
b := decoder.reserve(1)
decoder.boolValue = b[0]
}
mask := byte(1 << decoder.boolBit)
decoder.boolBit = (decoder.boolBit + 1) % 8
x := ((decoder.boolValue & mask) != 0)
return x
}
// Int8 decode an int8 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Int8() int8 {
return int8(decoder.Uint8())
}
// Uint8 decode a uint8 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Uint8() uint8 {
b := decoder.reserve(1)
x := b[0]
return x
}
// Int16 decode an int16 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Int16(packed bool) int16 {
if packed {
x, _ := decoder.Varint()
return int16(x)
}
return int16(decoder.Uint16(false))
}
// Uint16 decode a uint16 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Uint16(packed bool) uint16 {
if packed {
x, _ := decoder.Uvarint()
return uint16(x)
}
b := decoder.reserve(2)
x := decoder.endian.Uint16(b)
return x
}
// Int32 decode an int32 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Int32(packed bool) int32 {
if packed {
x, _ := decoder.Varint()
return int32(x)
}
return int32(decoder.Uint32(false))
}
// Uint32 decode a uint32 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Uint32(packed bool) uint32 {
if packed {
x, _ := decoder.Uvarint()
return uint32(x)
}
b := decoder.reserve(4)
x := decoder.endian.Uint32(b)
return x
}
// Int64 decode an int64 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Int64(packed bool) int64 {
if packed {
x, _ := decoder.Varint()
return x
}
return int64(decoder.Uint64(false))
}
// Uint64 decode a uint64 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Uint64(packed bool) uint64 {
if packed {
x, _ := decoder.Uvarint()
return x
}
b := decoder.reserve(8)
x := decoder.endian.Uint64(b)
return x
}
// Float32 decode a float32 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Float32() float32 {
x := math.Float32frombits(decoder.Uint32(false))
return x
}
// Float64 decode a float64 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Float64() float64 {
x := math.Float64frombits(decoder.Uint64(false))
return x
}
// Complex64 decode a complex64 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Complex64() complex64 {
x := complex(decoder.Float32(), decoder.Float32())
return x
}
// Complex128 decode a complex128 value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) Complex128() complex128 {
x := complex(decoder.Float64(), decoder.Float64())
return x
}
// String decode a string value from Decoder buffer.
// It will panic if buffer is not enough.
func (decoder *Decoder) String() string {
s, _ := decoder.Uvarint()
size := int(s)
b := decoder.reserve(size)
return string(b)
}
// Int decode an int value from Decoder buffer.
// It will panic if buffer is not enough.
// It use Varint() to decode as varint(1~10 bytes)
func (decoder *Decoder) Int() int {
n, _ := decoder.Varint()
return int(n)
}
// Uint decode a uint value from Decoder buffer.
// It will panic if buffer is not enough.
// It use Uvarint() to decode as uvarint(1~10 bytes)
func (decoder *Decoder) Uint() uint {
n, _ := decoder.Uvarint()
return uint(n)
}
// Varint decode an int64 value from Decoder buffer with varint(1~10 bytes).
// It will panic if buffer is not enough.
func (decoder *Decoder) Varint() (int64, int) {
ux, n := decoder.Uvarint() // ok to continue in presence of error
return ToVarint(ux), n
}
// Uvarint decode a uint64 value from Decoder buffer with varint(1~10 bytes).
// It will panic if buffer is not enough.
// It will return n <= 0 if varint error
func (decoder *Decoder) Uvarint() (uint64, int) {
var x uint64
var bit uint
var i int
for i = 0; i < MaxVarintLen64; i++ {
b := decoder.Uint8()
x |= uint64(b&0x7f) << bit
if b < 0x80 {
if i > 9 || i == 9 && b > 1 {
break // overflow
}
return x, i + 1
}
bit += 7
}
//return 0, 0
panic(fmt.Errorf("binary.Decoder.Uvarint: overflow 64-bits value(pos:%d/%d)", decoder.Len(), decoder.Cap()))
}
// Value decode an interface value from Encoder buffer.
// x must be interface of pointer for modify.
// It will return none-nil error if x contains unsupported types
// or buffer is not enough.
// It will check if x implements interface BinaryEncoder and use x.Encode first.
func (decoder *Decoder) Value(x interface{}) (err error) {
defer func() {
if info := recover(); info != nil {
err = info.(error)
assert(err != nil, info)
}
}()
decoder.resetBoolCoder() //reset bool reader
if decoder.fastValue(x) { //fast value path
return nil
}
v := reflect.ValueOf(x)
if p, ok := x.(BinaryDecoder); ok {
size := 0
if sizer, _ok := x.(BinarySizer); _ok { //interface verification
size = sizer.Size()
} else {
panic(fmt.Errorf("expect but not BinarySizer: %s", v.Type().String()))
}
if _, _ok := x.(BinaryEncoder); !_ok { //interface verification
panic(fmt.Errorf("unexpect but not BinaryEncoder: %s", v.Type().String()))
}
err := p.Decode(decoder.buff[decoder.pos:])
if err != nil {
return err
}
decoder.reserve(size)
return nil
}
if _, _ok := x.(BinarySizer); _ok { //interface verification
panic(fmt.Errorf("unexpected BinarySizer: %s", v.Type().String()))
}
if _, _ok := x.(BinaryEncoder); _ok { //interface verification
panic(fmt.Errorf("unexpected BinaryEncoder: %s", v.Type().String()))
}
if v.Kind() == reflect.Ptr { //only support decode for pointer interface
return decoder.value(v, true, false)
}
return fmt.Errorf("binary.Decoder.Value: non-pointer type %s", v.Type().String())
}
func (decoder *Decoder) value(v reflect.Value, topLevel bool, packed bool) error {
// check Packer interface for every value is perfect
// but decoder is too costly
//
// if t := v.Type(); t.Implements(tUnpacker) {
// if !t.Implements(tPacker) { //interface verification
// panic(fmt.Errorf("unexpect but not Packer: %s", v.Type().String()))
// }
// if !t.Implements(tSizer) { //interface verification
// panic(fmt.Errorf("expect but not Sizer: %s", t.String()))
// }
// unpacker := v.Interface().(PackUnpacker)
// size := unpacker.Size()
// err := unpacker.Unpack(decoder.buff[decoder.pos:])
// if err != nil {
// return err
// }
// decoder.reserve(size)
// return nil
// } else {
// //interface verification
// if t.Implements(tSizer) {
// panic(fmt.Errorf("unexpected Sizer: %s", t.String()))
// }
// if t.Implements(tPacker) {
// panic(fmt.Errorf("unexpected Packer: %s", t.String()))
// }
// }
switch k := v.Kind(); k {
case reflect.Int:
v.SetInt(int64(decoder.Int()))
case reflect.Uint:
v.SetUint(uint64(decoder.Uint()))
case reflect.Bool:
v.SetBool(decoder.Bool())
case reflect.Int8:
v.SetInt(int64(decoder.Int8()))
case reflect.Int16:
v.SetInt(int64(decoder.Int16(packed)))
case reflect.Int32:
v.SetInt(int64(decoder.Int32(packed)))
case reflect.Int64:
v.SetInt(decoder.Int64(packed))
case reflect.Uint8:
v.SetUint(uint64(decoder.Uint8()))
case reflect.Uint16:
v.SetUint(uint64(decoder.Uint16(packed)))
case reflect.Uint32:
v.SetUint(uint64(decoder.Uint32(packed)))
case reflect.Uint64:
v.SetUint(decoder.Uint64(packed))
case reflect.Float32:
v.SetFloat(float64(decoder.Float32()))
case reflect.Float64:
v.SetFloat(decoder.Float64())
case reflect.Complex64:
v.SetComplex(complex128(decoder.Complex64()))
case reflect.Complex128:
v.SetComplex(decoder.Complex128())
case reflect.String:
v.SetString(decoder.String())
case reflect.Slice, reflect.Array:
if !validUserType(v.Type().Elem()) { //verify array element is valid
return fmt.Errorf("binary.Decoder.Value: unsupported type %s", v.Type().String())
}
if decoder.boolArray(v) < 0 { //deal with bool array first
s, _ := decoder.Uvarint()
size := int(s)
if size > 0 && k == reflect.Slice { //make a new slice
ns := reflect.MakeSlice(v.Type(), size, size)
v.Set(ns)
}
l := v.Len()
for i := 0; i < size; i++ {
if i < l {
assert(decoder.value(v.Index(i), false, packed) == nil, "")
} else {
skiped := decoder.skipByType(v.Type().Elem(), packed)
assert(skiped >= 0, v.Type().Elem().String()) //I'm sure here cannot find unsupported type
}
}
}
case reflect.Map:
t := v.Type()
kt := t.Key()
vt := t.Elem()
if !validUserType(kt) ||
!validUserType(vt) { //verify map key and value type are both valid
return fmt.Errorf("binary.Decoder.Value: unsupported type %s", v.Type().String())
}
if v.IsNil() {
newmap := reflect.MakeMap(v.Type())
v.Set(newmap)
}
s, _ := decoder.Uvarint()
size := int(s)
for i := 0; i < size; i++ {
key := reflect.New(kt).Elem()
value := reflect.New(vt).Elem()
assert(decoder.value(key, false, packed) == nil, "")
assert(decoder.value(value, false, packed) == nil, "")
v.SetMapIndex(key, value)
}
case reflect.Struct:
return queryStruct(v.Type()).decode(decoder, v)
default:
if newPtr(v, decoder, topLevel) {
if !v.IsNil() {
return decoder.value(v.Elem(), false, packed)
}
} else {
return fmt.Errorf("binary.Decoder.Value: unsupported type %s", v.Type().String())
}
}
return nil
}
func (decoder *Decoder) fastValue(x interface{}) bool {
switch d := x.(type) {
case *int:
*d = decoder.Int()
case *uint:
*d = decoder.Uint()
case *bool:
*d = decoder.Bool()
case *int8:
*d = decoder.Int8()
case *uint8:
*d = decoder.Uint8()
case *int16:
*d = decoder.Int16(false)
case *uint16:
*d = decoder.Uint16(false)
case *int32:
*d = decoder.Int32(false)
case *uint32:
*d = decoder.Uint32(false)
case *float32:
*d = decoder.Float32()
case *int64:
*d = decoder.Int64(false)
case *uint64:
*d = decoder.Uint64(false)
case *float64:
*d = decoder.Float64()
case *complex64:
*d = decoder.Complex64()
case *complex128:
*d = decoder.Complex128()
case *string:
*d = decoder.String()
case *[]bool:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]bool, l)
var b []byte
for i := 0; i < l; i++ {
_, bit := i/8, i%8
mask := byte(1 << uint(bit))
if bit == 0 {
b = decoder.reserve(1)
}
x := ((b[0] & mask) != 0)
(*d)[i] = x
}
case *[]int:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]int, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Int()
}
case *[]uint:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]uint, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Uint()
}
case *[]int8:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]int8, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Int8()
}
case *[]uint8:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]uint8, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Uint8()
}
case *[]int16:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]int16, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Int16(false)
}
case *[]uint16:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]uint16, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Uint16(false)
}
case *[]int32:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]int32, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Int32(false)
}
case *[]uint32:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]uint32, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Uint32(false)
}
case *[]int64:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]int64, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Int64(false)
}
case *[]uint64:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]uint64, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Uint64(false)
}
case *[]float32:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]float32, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Float32()
}
case *[]float64:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]float64, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Float64()
}
case *[]complex64:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]complex64, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Complex64()
}
case *[]complex128:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]complex128, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.Complex128()
}
case *[]string:
s, _ := decoder.Uvarint()
l := int(s)
*d = make([]string, l)
for i := 0; i < l; i++ {
(*d)[i] = decoder.String()
}
default:
return false
}
return true
}
func (decoder *Decoder) skipByType(t reflect.Type, packed bool) int {
if s := fixedTypeSize(t); s > 0 {
if packedType := packedIntsType(t); packedType > 0 && packed {
switch packedType {
case _SignedInts:
_, n := decoder.Varint()
return n
case _UnsignedInts:
_, n := decoder.Uvarint()
return n
}
} else {
decoder.Skip(s)
return s
}
}
switch t.Kind() {
case reflect.Ptr:
if isNotNil := decoder.Bool(); isNotNil {
return decoder.skipByType(t.Elem(), packed) + 1
}
return 1
case reflect.Bool:
decoder.Bool()
return 1
case reflect.Int:
_, n := decoder.Varint()
return n
case reflect.Uint:
_, n := decoder.Uvarint()
return n
case reflect.String:
s, n := decoder.Uvarint()
size := int(s) //string length and data
decoder.Skip(size)
return size + n
case reflect.Slice, reflect.Array:
s, sLen := decoder.Uvarint()
cnt := int(s)
elemtype := t.Elem()
if s := fixedTypeSize(elemtype); s > 0 {
size := cnt * s
decoder.Skip(size)
return size
}
if elemtype.Kind() == reflect.Bool { //compressed bool array
totalSize := sizeofBoolArray(cnt)
size := totalSize - SizeofUvarint(uint64(cnt)) //cnt has been read
decoder.Skip(size)
return totalSize
}
sum := sLen //array size
for i, n := 0, cnt; i < n; i++ {
s := decoder.skipByType(elemtype, packed)
assert(s >= 0, "skip fail: "+elemtype.String()) //I'm sure here cannot find unsupported type
sum += s
}
return sum
case reflect.Map:
s, sLen := decoder.Uvarint()
cnt := int(s)
kt := t.Key()
vt := t.Elem()
sum := sLen //array size
for i, n := 0, cnt; i < n; i++ {
sum += decoder.skipByType(kt, packed)
sum += decoder.skipByType(vt, packed)
}
return sum
case reflect.Struct:
return queryStruct(t).decodeSkipByType(decoder, t, packed)
}
return -1
}
// decode bool array
func (decoder *Decoder) boolArray(v reflect.Value) int {
if k := v.Kind(); k == reflect.Slice || k == reflect.Array {
if v.Type().Elem().Kind() == reflect.Bool {
_l, _ := decoder.Uvarint()
l := int(_l)
if k == reflect.Slice && l > 0 { //make a new slice
v.Set(reflect.MakeSlice(v.Type(), l, l))
}
var b []byte
for i := 0; i < l; i++ {
_, bit := i/8, i%8
mask := byte(1 << uint(bit))
if bit == 0 {
b = decoder.reserve(1)
}
x := ((b[0] & mask) != 0)
v.Index(i).SetBool(x)
}
return sizeofBoolArray(l)
}
}
return -1
}