-
Notifications
You must be signed in to change notification settings - Fork 2
/
varying_data.go
68 lines (53 loc) · 1.33 KB
/
varying_data.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
package goscale
/*
Ref: https://spec.polkadot.network/#defn-varrying-data-type)
SCALE Varying Data Type.
*/
import (
"bytes"
"errors"
"math"
)
var (
errDecodingFuncNotFound = errors.New("varying data: decode func not found")
errExceedsU8Length = errors.New("exceeds uint8 length")
)
type VaryingData []Encodable
func NewVaryingData(values ...Encodable) VaryingData {
if len(values) > math.MaxUint8 {
panic("exceeds uint8 length")
}
result := make([]Encodable, 0, len(values))
result = append(result, values...)
return result
}
func (vd VaryingData) Encode(buffer *bytes.Buffer) error {
for _, v := range vd {
err := v.Encode(buffer)
if err != nil {
return err
}
}
return nil
}
func DecodeVaryingData(decodeFuncs []func(buffer *bytes.Buffer) []Encodable, buffer *bytes.Buffer) (VaryingData, error) {
funcsLen := len(decodeFuncs)
if funcsLen > math.MaxUint8 {
return VaryingData{}, errExceedsU8Length
}
index, err := DecodeU8(buffer)
if err != nil {
return VaryingData{}, err
}
if int(index) > funcsLen-1 {
return VaryingData{}, errDecodingFuncNotFound
}
decoded := decodeFuncs[index](buffer)
args := make([]Encodable, 0, len(decoded)+1)
args = append(args, index)
args = append(args, decoded...)
return NewVaryingData(args...), nil
}
func (vd VaryingData) Bytes() []byte {
return EncodedBytes(vd)
}