-
Notifications
You must be signed in to change notification settings - Fork 19
/
schema.go
143 lines (131 loc) · 2.27 KB
/
schema.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
package schema
import (
"strconv"
"strings"
)
type Type struct {
Kind byte
Static bool
Size int
// tuple
Fields []Type
// array
Length int
Elem *Type
}
func Static() Type {
return Type{Kind: 's', Size: 32, Static: true}
}
func Dynamic() Type {
return Type{Kind: 'd'}
}
func Array(e Type) Type {
return Type{
Kind: 'a',
Static: false,
Size: 0,
Elem: &e,
Length: 0,
}
}
func ArrayK(k int, e Type) Type {
t := Type{Kind: 'a', Elem: &e, Length: k}
if !e.static() {
return t
}
t.Static = true
t.Size = k * e.size()
return t
}
func Tuple(fields ...Type) Type {
t := Type{Kind: 't', Static: true, Fields: fields}
for _, f := range fields {
if f.static() {
t.Size += f.size()
continue
}
t.Size = 0
t.Static = false
break
}
return t
}
func (t Type) static() bool {
switch {
case t.Kind == 'd':
return false
case t.Kind == 'a' && t.Length == 0:
return false
case t.Kind == 'a' && !t.Elem.static():
return false
case t.Kind == 't':
for _, f := range t.Fields {
if !f.static() {
return false
}
}
}
return true
}
func (t Type) size() int {
if !t.static() {
return 0
}
switch {
case t.Kind == 'a' && t.Elem.static():
return t.Length * t.Elem.size()
case t.Kind == 't':
var n int
for _, t := range t.Fields {
n += t.size()
}
return n
default:
return 32
}
}
func Parse(s string) Type {
s = strings.ReplaceAll(s, " ", "")
switch {
case strings.HasSuffix(s, "]"):
var num string
for i := len(s) - 2; i != 0; i-- {
if s[i] == '[' {
break
}
num += string(s[i])
}
if len(num) == 0 {
return Array(Parse(s[:len(s)-2]))
}
k, err := strconv.Atoi(num)
if err != nil {
panic("abi/schema: array contains non-number length")
}
return ArrayK(k, Parse(s[:len(s)-len(num)-2]))
case strings.HasPrefix(s, "("):
var (
types []Type
list = s[1 : len(s)-1]
depth int
)
for i, j := 0, 0; i < len(list); i++ {
switch {
case i+1 == len(list):
types = append(types, Parse(list[j:i+1]))
case depth == 0 && list[i] == ',':
types = append(types, Parse(list[j:i]))
j = i + 1
case list[i] == '(':
depth++
case list[i] == ')':
depth--
}
}
return Tuple(types...)
case s == "bytes" || s == "string":
return Dynamic()
default:
return Static()
}
}