forked from landonia/gobert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.go
878 lines (725 loc) · 15.7 KB
/
decode.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
package bert
import (
"bytes"
"compress/zlib"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"math/big"
"reflect"
"sort"
"strconv"
)
var (
ErrBadMagic error = errors.New("bad magic")
ErrUnknownType error = errors.New("unknown type")
ErrMissingAtom error = errors.New("missing Atom")
ErrEOF error = errors.New("Unexpected EOF")
// The atom distribution cache
cache = DistributionHeader{}
)
func readLength(r io.Reader, length int64) ([]byte, error) {
bits, err := ioutil.ReadAll(io.LimitReader(r, length))
if err != nil {
return nil, err
}
if int64(len(bits)) != length {
return nil, ErrEOF
}
return bits, nil
}
func read1(r io.Reader) (int, error) {
bits, err := readLength(r, 1)
if err != nil {
return 0, err
}
ui8 := uint8(bits[0])
return int(ui8), nil
}
func read2(r io.Reader) (int, error) {
bits, err := readLength(r, 2)
if err != nil {
return 0, err
}
ui16 := binary.BigEndian.Uint16(bits)
return int(ui16), nil
}
func read4(r io.Reader) (int, error) {
bits, err := readLength(r, 4)
if err != nil {
return 0, err
}
ui32 := binary.BigEndian.Uint32(bits)
return int(ui32), nil
}
func readCompressed(r io.Reader) (Term, error) {
_, err := read4(r)
if err != nil {
return nil, err
}
// Attempt to decode the bytes
reader, err := zlib.NewReader(r)
if err != nil {
return nil, err
}
defer reader.Close()
// Start reading from the new reader
return readTag(reader)
}
func readDistributionHeader(r io.Reader) (Term, error) {
// Attempt to parse the header into the cache
if err := cache.Update(r); err != nil {
return nil, err
}
// Cache has now been updated so parse the next flag
return readTag(r)
}
func readSmallInt(r io.Reader) (int, error) {
return read1(r)
}
func readInt(r io.Reader) (int, error) {
// An integer is a Signed 32bit value
// Depending on whether we are on a 32 or 64 bit system the default
// int size will change appropriately. Therefore the sign of
// a number will be lost when compiling on a 64 bit system but
// will work on a 32 bit. The way around this is to cast to a
// int32 and then cast back to an int which will keep the sign of the number
val, err := read4(r)
if err != nil {
return val, err
}
return int(int32(val)), nil
}
func readSmallBignum(r io.Reader) (big.Int, error) {
numLen, err := read1(r)
if err != nil {
return *big.NewInt(0), err
}
return readBigNum(r, numLen)
}
func readLargeBignum(r io.Reader) (big.Int, error) {
numLen, err := read4(r)
if err != nil {
return *big.NewInt(0), err
}
return readBigNum(r, numLen)
}
func readBigNum(r io.Reader, numLen int) (big.Int, error) {
sign, err := read1(r)
if err != nil {
return *big.NewInt(0), err
}
bits, err := readLength(r, int64(numLen))
if err != nil {
return *big.NewInt(0), err
}
// The bytes are stored with the LSB byte stored first
// Reverse the array to get BigEndian
var bigEndBits []byte
for i := len(bits) - 1; i >= 0; i-- {
bigEndBits = append(bigEndBits, bits[i])
}
// Parse the big int
bigNum := &big.Int{}
bigNum.SetBytes(bigEndBits)
if sign == 1 {
// Then the number is negative
bigNum = bigNum.Neg(bigNum)
}
return *bigNum, nil
}
func readFloat(r io.Reader) (float32, error) {
bits, err := readLength(r, 31)
if err != nil {
return 0, err
}
// ParseFloat doesn't like trailing 0s
var i int
for i = 0; i < len(bits); i++ {
if bits[i] == 0 {
break
}
}
f, err := strconv.ParseFloat(string(bits[0:i]), 32)
if err != nil {
return 0, err
}
return float32(f), nil
}
func readNewFloat(r io.Reader) (float64, error) {
bits, err := readLength(r, 8)
if err != nil {
return 0, err
}
ui64 := binary.BigEndian.Uint64(bits)
return math.Float64frombits(ui64), nil
}
func readAtomRef(r io.Reader) (Atom, error) {
atomCacheRefIndex, err := read1(r)
if err != nil {
return Atom(""), err
}
atom, err := cache.GetAtom(uint8(atomCacheRefIndex))
if err != nil {
return Atom(""), err
}
return *atom, nil
}
func readAtom(r io.Reader) (Atom, error) {
str, err := readString(r)
return Atom(str), err
}
func readSmallAtom(r io.Reader) (Atom, error) {
str, err := readSmallString(r)
return Atom(str), err
}
func readSmallTuple(r io.Reader) (Term, error) {
size, err := read1(r)
if err != nil {
return nil, err
}
tuple := make([]Term, size)
for i := 0; i < size; i++ {
term, err := readTag(r)
if err != nil {
return nil, err
}
switch a := term.(type) {
case Atom:
if a == BertAtom {
return readComplex(r)
}
}
tuple[i] = term
}
return tuple, nil
}
func readLargeTuple(r io.Reader) (Term, error) {
size, err := read4(r)
if err != nil {
return nil, err
}
tuple := make([]Term, size)
for i := uint32(0); i < uint32(size); i++ {
term, err := readTag(r)
if err != nil {
return nil, err
}
switch a := term.(type) {
case Atom:
if a == BertAtom {
return readComplex(r)
}
}
tuple[i] = term
}
return tuple, nil
}
func readNil(r io.Reader) ([]Term, error) {
list := make([]Term, 0)
return list, nil
}
func readString(r io.Reader) (string, error) {
size, err := read2(r)
if err != nil {
return "", err
}
str, err := readLength(r, int64(size))
if err != nil {
return "", err
}
return string(str), nil
}
func readSmallString(r io.Reader) (string, error) {
size, err := read1(r)
if err != nil {
return "", err
}
str, err := readLength(r, int64(size))
if err != nil {
return "", err
}
return string(str), nil
}
func readList(r io.Reader) ([]Term, error) {
size, err := read4(r)
if err != nil {
return nil, err
}
list := make([]Term, size)
for i := 0; i < size; i++ {
term, err := readTag(r)
if err != nil {
return nil, err
}
list[i] = term
}
read1(r)
return list, nil
}
// use a specific type for the bin type so that
type bintag []uint8
// String will attempt to print the value as a string
func (b bintag) String() string {
return fmt.Sprintf("%s", string(b))
}
func readBin(r io.Reader) (bintag, error) {
size, err := read4(r)
if err != nil {
return bintag{}, err
}
bytes, err := readLength(r, int64(size))
if err != nil {
return bintag{}, err
}
return bintag(bytes), nil
}
// maptag is a specific type that allows us to override the print statement to always ensure
// that the keys are printed in order
type maptag map[Term]Term
func (m maptag) String() string {
// Cast back to the map type
var keys []string
realKeys := map[string]Term{}
for k := range m {
// Turn the key into a string representation in order to quickly sort it
key := fmt.Sprintf("%v", k)
keys = append(keys, key)
realKeys[key] = k
}
sort.Strings(keys)
// To perform the opertion you want
r := "{"
for _, k := range keys {
// get the real key for this stringified version
rk := realKeys[k]
r += fmt.Sprintf("%v:%v,", rk, m[rk])
}
r += "}"
return r
}
func readMap(r io.Reader) (maptag, error) {
pairs, err := read4(r)
if err != nil {
return nil, err
}
m := make(map[Term]Term)
for i := 0; i < pairs; i++ {
key, err := readTag(r)
if err != nil {
return nil, err
}
value, err := readTag(r)
if err != nil {
return nil, err
}
m[key] = value
}
return maptag(m), nil
}
func readComplex(r io.Reader) (Term, error) {
term, err := readTag(r)
if err != nil {
return term, err
}
switch kind := term.(type) {
case Atom:
switch kind {
case NilAtom:
return nil, nil
case TrueAtom:
return true, nil
case FalseAtom:
return false, nil
}
}
return term, nil
}
func readReference(r io.Reader) (Reference, error) {
reference := Reference{}
term, err := readTag(r)
if err != nil {
return reference, err
}
switch a := term.(type) {
case Atom:
reference.Node = a
default:
return reference, ErrMissingAtom
}
id, err := read4(r)
if err != nil {
return reference, err
}
reference.ID = uint32(id)
creation, err := read1(r)
if err != nil {
return reference, err
}
reference.Creation = uint8(creation)
return reference, nil
}
func readNewReference(r io.Reader) (NewReference, error) {
reference := NewReference{}
len, err := read2(r)
if err != nil {
return reference, err
}
term, err := readTag(r)
if err != nil {
return reference, err
}
switch a := term.(type) {
case Atom:
reference.Node = a
default:
return reference, ErrMissingAtom
}
creation, err := read1(r)
if err != nil {
return reference, err
}
reference.Creation = uint8(creation)
// Extract the IDS
ids := make([]uint32, len)
for i := 0; i < len; i++ {
id, err := read4(r)
if err != nil {
return reference, err
}
ids[i] = uint32(id)
}
reference.ID = ids
return reference, nil
}
func readPort(r io.Reader) (Port, error) {
port := Port{}
term, err := readTag(r)
if err != nil {
return port, err
}
switch a := term.(type) {
case Atom:
port.Node = a
default:
return port, ErrMissingAtom
}
id, err := read4(r)
if err != nil {
return port, err
}
port.ID = uint32(id)
creation, err := read1(r)
if err != nil {
return port, err
}
port.Creation = uint8(creation)
return port, nil
}
func readPid(r io.Reader) (Pid, error) {
pid := Pid{}
term, err := readTag(r)
if err != nil {
return pid, err
}
switch a := term.(type) {
case Atom:
pid.Node = a
default:
return pid, ErrMissingAtom
}
id, err := read4(r)
if err != nil {
return pid, err
}
pid.ID = uint32(id)
serial, err := read4(r)
if err != nil {
return pid, err
}
pid.Serial = uint32(serial)
creation, err := read1(r)
if err != nil {
return pid, err
}
pid.Creation = uint8(creation)
return pid, nil
}
func readFunc(r io.Reader) (Func, error) {
function := Func{}
numfree, err := read4(r)
if err != nil {
return function, err
}
term, err := readTag(r)
if err != nil {
return function, err
}
switch pid := term.(type) {
case Pid:
function.Pid = pid
default:
return function, ErrUnknownType
}
term, err = readTag(r)
if err != nil {
return function, err
}
switch module := term.(type) {
case Atom:
function.Module = module
default:
return function, ErrUnknownType
}
term, err = readTag(r)
if err != nil {
return function, err
}
switch v := reflect.ValueOf(term); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
function.Index = uint32(v.Int())
default:
return function, ErrUnknownType
}
term, err = readTag(r)
if err != nil {
return function, err
}
switch v := reflect.ValueOf(term); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
function.Uniq = uint32(v.Int())
default:
return function, ErrUnknownType
}
// Extract the free vars
freeVars := make([]Term, numfree)
for i := 0; i < numfree; i++ {
term, err := readTag(r)
if err != nil {
return function, err
}
freeVars[i] = term
}
function.FreeVars = freeVars
return function, nil
}
func readNewFunc(r io.Reader) (NewFunc, error) {
function := NewFunc{}
// Get size of the func including the 4 bytes itself
size, err := read4(r)
if err != nil {
return function, err
}
// Only allow the next size-4 bytes to be read
lr := io.LimitReader(r, int64(size-4))
arity, err := read1(lr)
if err != nil {
return function, err
}
function.Arity = uint8(arity)
uniq, err := readLength(r, 16)
if err != nil {
return function, err
}
function.Uniq = uniq
index, err := read4(lr)
if err != nil {
return function, err
}
function.Index = uint32(index)
numfree, err := read4(lr)
if err != nil {
return function, err
}
term, err := readTag(lr)
if err != nil {
return function, err
}
switch module := term.(type) {
case Atom:
function.Module = module
default:
return function, ErrUnknownType
}
term, err = readTag(lr)
if err != nil {
return function, err
}
switch v := reflect.ValueOf(term); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
function.OldIndex = uint32(v.Int())
default:
return function, ErrUnknownType
}
term, err = readTag(lr)
if err != nil {
return function, err
}
switch v := reflect.ValueOf(term); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
function.OldUnique = uint32(v.Int())
default:
return function, ErrUnknownType
}
term, err = readTag(lr)
if err != nil {
return function, err
}
switch pid := term.(type) {
case Pid:
function.Pid = pid
default:
return function, ErrUnknownType
}
// Extract the free vars
freeVars := make([]Term, numfree)
for i := 0; i < numfree; i++ {
term, err := readTag(lr)
if err != nil {
return function, err
}
freeVars[i] = term
}
function.FreeVars = freeVars
return function, nil
}
func readExport(r io.Reader) (Export, error) {
export := Export{}
term, err := readTag(r)
if err != nil {
return export, err
}
switch module := term.(type) {
case Atom:
export.Module = module
default:
return export, ErrMissingAtom
}
term, err = readTag(r)
if err != nil {
return export, err
}
switch function := term.(type) {
case Atom:
export.Function = function
default:
return export, ErrMissingAtom
}
term, err = readTag(r)
if err != nil {
return export, err
}
switch v := reflect.ValueOf(term); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
export.Arity = uint8(v.Int())
default:
return export, ErrUnknownType
}
return export, nil
}
func readTag(r io.Reader) (Term, error) {
tag, err := read1(r)
if err != nil {
return nil, err
}
switch tag {
case CompressedTag:
return readCompressed(r)
case DistributionHeaderTag:
return readDistributionHeader(r)
case SmallIntTag:
return readSmallInt(r)
case IntTag:
return readInt(r)
case SmallBignumTag:
return readSmallBignum(r)
case LargeBignumTag:
return readLargeBignum(r)
case FloatTag:
return readFloat(r)
case NewFloatTag:
return readNewFloat(r)
case AtomCacheRefTag:
return readAtomRef(r)
case AtomTag, AtomUtf8Tag:
return readAtom(r)
case SmallAtomTag, SmallAtomUtf8Tag:
return readSmallAtom(r)
case SmallTupleTag:
return readSmallTuple(r)
case LargeTupleTag:
return readLargeTuple(r)
case NilTag:
return readNil(r)
case StringTag:
return readString(r)
case ListTag:
return readList(r)
case BinTag:
return readBin(r)
case MapTag:
return readMap(r)
case ReferenceTag:
return readReference(r)
case NewReferenceTag:
return readNewReference(r)
case PortTag:
return readPort(r)
case PidTag:
return readPid(r)
case FunTag:
return readFunc(r)
case NewFunTag:
return readNewFunc(r)
case ExportTag:
return readExport(r)
}
return nil, ErrUnknownType
}
// DecodeFrom decodes a Term from r and returns it or an error.
func DecodeFrom(r io.Reader) (Term, error) {
version, err := read1(r)
if err != nil {
return nil, err
}
// check protocol version
if version != VersionTag {
return nil, ErrBadMagic
}
return readTag(r)
}
// Decode decodes a Term from data and returns it or an error.
func Decode(data []byte) (Term, error) { return DecodeFrom(bytes.NewBuffer(data)) }
// UnmarshalFrom decodes a value from r, stores it in val, and returns any
// error encountered.
func UnmarshalFrom(r io.Reader, val interface{}) (err error) {
result, _ := DecodeFrom(r)
value := reflect.ValueOf(val).Elem()
switch v := value; v.Kind() {
case reflect.Struct:
slice := reflect.ValueOf(result)
for i := 0; i < slice.Len(); i++ {
e := slice.Index(i).Elem()
v.Field(i).Set(e)
}
}
return nil
}
// Unmarshal decodes a value from data, stores it in val, and returns any error
// encountered.
func Unmarshal(data []byte, val interface{}) (err error) {
return UnmarshalFrom(bytes.NewBuffer(data), val)
}
// UnmarshalRequest decodes a BURP from r and returns it as a Request.
func UnmarshalRequest(r io.Reader) (Request, error) {
var req Request
size, err := read4(r)
if err != nil {
return req, err
}
err = UnmarshalFrom(io.LimitReader(r, int64(size)), &req)
return req, err
}