-
Notifications
You must be signed in to change notification settings - Fork 2
/
dictionary.go
75 lines (60 loc) · 1.29 KB
/
dictionary.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
package goscale
/*
Ref: https://spec.polkadot.network/#defn-scale-dictionary
SCALE Dictionary type translates to Go's map type.
*/
import (
"bytes"
"sort"
)
type Comparable interface {
Encodable
Ordered
}
type Dictionary[K Comparable, V Encodable] map[K]V
func (d Dictionary[K, V]) Encode(buffer *bytes.Buffer) error {
err := ToCompact(len(d)).Encode(buffer)
if err != nil {
return err
}
keys := make([]K, 0)
for k := range d {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
for _, k := range keys {
v := d[k]
err := k.Encode(buffer)
if err != nil {
return err
}
err = v.Encode(buffer)
if err != nil {
return err
}
}
return nil
}
func (d Dictionary[K, V]) Bytes() []byte {
return EncodedBytes(d)
}
func DecodeDictionary[K Comparable, V Encodable](buffer *bytes.Buffer) (Dictionary[K, V], error) {
result := Dictionary[K, V]{}
v, err := DecodeCompact[U128](buffer)
if err != nil {
return nil, err
}
size := int(v.ToBigInt().Int64())
for i := 0; i < size; i++ {
key, err := decodeByType(*new(K), buffer)
if err != nil {
return Dictionary[K, V]{}, err
}
value, err := decodeByType(*new(V), buffer)
if err != nil {
return Dictionary[K, V]{}, err
}
result[key.(K)] = value.(V)
}
return result, nil
}