forked from ferranbt/fastssz
/
size.go
executable file
·106 lines (93 loc) · 2.58 KB
/
size.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
package main
import (
"fmt"
"strconv"
"strings"
)
// size creates a function that returns the SSZ size of the struct. There are two components:
// 1. Fixed: Size that we can determine at compilation time (i.e. uint, fixed bytes, fixed vector...)
// 2. Dynamic: Size that depends on the input (i.e. lists, dynamic containers...)
// Note that if any of the internal fields of the struct is nil, we will not fail, only not add up
// that field to the size. It is up to other methods like marshal to fail on that scenario.
func (e *env) size(name string, v *Value) string {
tmpl := `// SizeSSZ returns the ssz encoded size in bytes for the {{.name}} object
func (:: *{{.name}}) SizeSSZ() (size int) {
size = {{.fixed}}{{if .dynamic}}
{{.dynamic}}
{{end}}
return
}`
str := execTmpl(tmpl, map[string]interface{}{
"name": name,
"fixed": v.n,
"dynamic": v.sizeContainer("size", true),
})
return appendObjSignature(str, v)
}
func (v *Value) sizeContainer(name string, start bool) string {
if !start {
tmpl := `{{if .check}} if ::.{{.name}} == nil {
::.{{.name}} = new({{.obj}})
}
{{end}} {{ .dst }} += ::.{{.name}}.SizeSSZ()`
check := true
if v.isListElem() {
check = false
}
if v.noPtr {
check = false
}
return execTmpl(tmpl, map[string]interface{}{
"name": v.name,
"dst": name,
"obj": v.objRef(),
"check": check,
})
}
out := []string{}
for indx, v := range v.o {
if !v.isFixed() {
out = append(out, fmt.Sprintf("// Field (%d) '%s'\n%s", indx, v.name, v.size(name)))
}
}
return strings.Join(out, "\n\n")
}
// 'name' is the name of target variable we assign the size too. We also use this function
// during marshalling to figure out the size of the offset
func (v *Value) size(name string) string {
if v.isFixed() {
if v.t == TypeContainer {
return v.sizeContainer(name, false)
}
if v.n == 1 {
return name + "++"
}
return name + " += " + strconv.Itoa(int(v.n))
}
switch v.t {
case TypeContainer, TypeReference:
return v.sizeContainer(name, false)
case TypeBitList:
fallthrough
case TypeBytes:
return fmt.Sprintf(name+" += len(::.%s)", v.name)
case TypeList:
fallthrough
case TypeVector:
if v.e.isFixed() {
return fmt.Sprintf("%s += len(::.%s) * %d", name, v.name, v.e.n)
}
v.e.name = v.name + "[ii]"
tmpl := `for ii := 0; ii < len(::.{{.name}}); ii++ {
{{.size}} += 4
{{.dynamic}}
}`
return execTmpl(tmpl, map[string]interface{}{
"name": v.name,
"size": name,
"dynamic": v.e.size(name),
})
default:
panic(fmt.Errorf("size not implemented for type %s", v.t.String()))
}
}