-
Notifications
You must be signed in to change notification settings - Fork 2
/
print_mem.go
108 lines (89 loc) · 2.27 KB
/
print_mem.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
package memalign
import (
"fmt"
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
"os"
"reflect"
"strconv"
)
type FieldInfo struct {
StrID string
FieldType reflect.Type
FieldName string
FieldSize int
}
type ColorFunc func(format string, a ...interface{}) string
var (
colorList []ColorFunc
)
func init() {
colorList = []ColorFunc{
color.RedString,
color.GreenString,
color.YellowString,
color.BlueString,
color.MagentaString,
color.CyanString,
}
}
func PrintStructAlignment(q interface{}) {
buff := make([]byte, 0)
if reflect.ValueOf(q).Kind() == reflect.Struct {
typeInfo := reflect.TypeOf(q)
fieldInfoList := make([]FieldInfo, typeInfo.NumField())
for i := 0; i < typeInfo.NumField(); i++ {
fieldInfoList[i].StrID = string(byte(i)+'A')
fieldInfoList[i].FieldType = typeInfo.Field(i).Type
fieldInfoList[i].FieldName = typeInfo.Field(i).Name
}
for i := 0; i < typeInfo.NumField(); i++ {
field := typeInfo.Field(i)
size := int(field.Type.Size())
fieldInfoList[i].FieldSize = size
// padding
paddSize := int(field.Offset) - len(buff)/2
//fmt.Println(i, ":", field.Offset, len(buff)/2)
for j := 0; j < paddSize; j++ {
buff = append(buff, '|', ' ')
}
for k := 0; k < size; k++ {
buff = append(buff, '|', byte(i+'A'))
}
}
if len(buff)%8 != 0 {
buff = append(buff, '|')
}
// print
// 1. Fields in struct
PrintStructInfo(fieldInfoList)
// 2. Memory layout
ColorFormatPrint(buff)
}
}
func PrintStructInfo(itemList []FieldInfo){
fmt.Println("---- Fields in struct ----")
table := tablewriter.NewWriter(os.Stdout)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetHeader([]string{"ID", "FieldType", "FieldName", "FieldSize"})
for _, item := range itemList {
table.Append([]string{item.StrID,item.FieldType.String(),
item.FieldName, strconv.Itoa(item.FieldSize)})
}
table.Render() // Send output
}
func ColorFormatPrint(buff []byte) {
fmt.Println("---- Memory layout ----")
for i := 0; i < len(buff); i++ {
if buff[i] >= 'A' && buff[i] <= 'Z' {
idx := int(buff[i]-'A') % len(colorList)
fmt.Printf(colorList[idx](string(buff[i])))
} else {
fmt.Printf(string(buff[i]))
}
if (i+1)%16 == 0 {
fmt.Println("|")
}
}
fmt.Printf("\ntotal cost: %v Bytes.\n", len(buff)/2)
}