-
Notifications
You must be signed in to change notification settings - Fork 24
/
bytes_viewer.go
61 lines (57 loc) · 1.32 KB
/
bytes_viewer.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
package ffmt
import (
"bytes"
"fmt"
"strconv"
"unicode"
"unsafe"
)
// BytesViewer bytes viewer
type BytesViewer []byte
// String returns view in hexadecimal
func (b BytesViewer) String() string {
if len(b) == 0 {
return invalid
}
const head = `
| Address | Hex | Text |
| -------: | :---------------------------------------------- | :--------------- |
`
const row = 16
result := make([]byte, 0, len(head)/2*(len(b)/16+3))
result = append(result, head...)
for i := 0; i < len(b); i += row {
result = append(result, "| "...)
result = append(result, fmt.Sprintf("%08x", i)...)
result = append(result, " | "...)
k := i + row
more := 0
if k >= len(b) {
more = k - len(b)
k = len(b)
}
for j := i; j != k; j++ {
if b[j] < 16 {
result = append(result, '0')
}
result = strconv.AppendUint(result, uint64(b[j]), 16)
result = append(result, ' ')
}
for j := 0; j != more; j++ {
result = append(result, " "...)
}
result = append(result, "| "...)
buf := bytes.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return ' '
}
return r
}, b[i:k])
result = append(result, buf...)
for j := 0; j != more; j++ {
result = append(result, ' ')
}
result = append(result, " |\n"...)
}
return *(*string)(unsafe.Pointer(&result))
}