-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstruct_test.go
84 lines (67 loc) · 1.77 KB
/
struct_test.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
package memlayout
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
const unoptimized = `
package foo
type Foo struct {
A string
B bool
C int64
D bool
E uint16
}
`
func TestOptimize(t *testing.T) {
require := require.New(t)
tmp, err := ioutil.TempDir(os.TempDir(), "tmp-memlayout")
require.NoError(err)
defer func() {
require.NoError(os.RemoveAll(tmp))
}()
path := filepath.Join(tmp, "test.go")
require.NoError(ioutil.WriteFile(path, []byte(unoptimized), 0755))
structs, err := StructsFromFile(path, []byte(unoptimized))
require.NoError(err)
require.Len(structs, 1)
optimized := Optimize(structs[0])
expected := Struct{
Name: "Foo",
Fields: []Field{
{Name: "A", Type: "string", Size: 16, Start: 0, End: 16, Align: 8},
{Name: "C", Type: "int64", Size: 8, Start: 16, End: 24, Align: 8},
{Name: "E", Type: "uint16", Size: 2, Start: 24, End: 26, Align: 2},
{Name: "B", Type: "bool", Size: 1, Start: 26, End: 27, Align: 1},
{Name: "D", Type: "bool", Size: 1, Start: 27, End: 28, Align: 1},
{Size: 4, IsPadding: true, Start: 28, End: 32}, // padding
},
}
structsEqual(t, expected, optimized)
}
func structsEqual(t *testing.T, expected, result Struct) {
t.Helper()
require := require.New(t)
require.Equal(expected.Name, result.Name)
require.Len(result.Fields, len(expected.Fields))
for i := range expected.Fields {
fieldsEqual(t, expected.Fields[i], result.Fields[i])
}
}
func fieldsEqual(t *testing.T, e, r Field) {
t.Helper()
if len(e.Children) > 0 {
require.Len(t, r.Children, len(e.Children))
for i := range e.Children {
e.Children[i].field = nil
r.Children[i].field = nil
fieldsEqual(t, e.Children[i], r.Children[i])
}
}
e.field = nil
r.field = nil
require.Equal(t, e, r)
}