-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayout.go
More file actions
101 lines (90 loc) · 2.27 KB
/
layout.go
File metadata and controls
101 lines (90 loc) · 2.27 KB
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
package main
import (
"fmt"
"sort"
"strings"
)
// LayoutField is a FieldSpec placed at a resolved offset within the struct.
type LayoutField struct {
FieldSpec
Offset int
PadAfter int // internal padding bytes between this field and the next
}
// Layout is the fully computed memory layout of a struct.
type Layout struct {
Fields []LayoutField
StructSize int
StructAlign int
InternalPad int // total avoidable padding
TrailingPad int // unavoidable trailing padding
}
func computeLayout(fields []FieldSpec) Layout {
if len(fields) == 0 {
return Layout{StructAlign: 1}
}
structAlign := 1
for _, f := range fields {
if f.Align > structAlign {
structAlign = f.Align
}
}
layoutFields := make([]LayoutField, len(fields))
offset := 0
internalPad := 0
for i, f := range fields {
// Advance offset to the next multiple of this field's alignment.
if rem := offset % f.Align; rem != 0 {
pad := f.Align - rem
if i > 0 {
layoutFields[i-1].PadAfter = pad
internalPad += pad
}
offset += pad
}
layoutFields[i] = LayoutField{
FieldSpec: f,
Offset: offset,
}
offset += f.Size
}
trailingPad := 0
if rem := offset % structAlign; rem != 0 {
trailingPad = structAlign - rem
}
return Layout{
Fields: layoutFields,
StructSize: offset + trailingPad,
StructAlign: structAlign,
InternalPad: internalPad,
TrailingPad: trailingPad,
}
}
// optimizeLayout sorts fields largest-alignment-first (greedy optimal) then
// recomputes the layout.
func optimizeLayout(fields []FieldSpec) Layout {
sorted := make([]FieldSpec, len(fields))
copy(sorted, fields)
sort.SliceStable(sorted, func(i, j int) bool {
if sorted[i].Align != sorted[j].Align {
return sorted[i].Align > sorted[j].Align
}
return sorted[i].Size > sorted[j].Size
})
return computeLayout(sorted)
}
// formatStruct renders the optimized field order as valid Go source.
func formatStruct(name string, layout Layout) string {
maxName := 0
for _, f := range layout.Fields {
if len(f.Name) > maxName {
maxName = len(f.Name)
}
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("type %s struct {\n", name))
for _, f := range layout.Fields {
sb.WriteString(fmt.Sprintf("\t%-*s %s\n", maxName, f.Name, f.TypeStr))
}
sb.WriteString("}")
return sb.String()
}