-
Notifications
You must be signed in to change notification settings - Fork 0
/
dump.go
112 lines (106 loc) · 1.77 KB
/
dump.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
109
110
111
112
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strings"
)
func getInFile(args []string) (io.Reader, error) {
var r io.Reader
var err error
if len(args) == 0 {
r = os.Stdin
} else {
r, err = os.Open(args[0])
}
if err != nil {
r = bufio.NewReader(r)
}
return r, err
}
func repr(c byte) byte {
if c < 32 || c > 126 {
return '.'
}
return c
}
func repr8(bs []byte) string {
out := ""
for _, b := range bs {
out += fmt.Sprintf("%02x ", int(b))
}
return out
}
func reprTxt(bs []byte) string {
out := "|"
for _, b := range bs {
out += string(repr(byte(b)))
}
return out + "|"
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func printLine(i int, buf []byte, out io.Writer) error {
l := len(buf)
m := min(8, l)
txt := fmt.Sprintf("%08x ", i)
txt += repr8(buf[0:m]) + " " + repr8(buf[m:l])
txt += strings.Repeat(" ", 60-len(txt))
_, err := fmt.Fprintf(out, "%s%s\n", txt, reprTxt(buf))
return err
}
func run(args []string, out io.Writer) error {
in, err := getInFile(args)
if err != nil {
return err
}
var buf, prv []byte
prevCmp := 1
for i := 0; ; i += 16 {
if len(buf) < 16 {
buf = make([]byte, 16)
}
n, err := io.ReadFull(in, buf)
if err == io.EOF {
return nil
}
if n < 16 {
buf = buf[:n]
}
cmp := bytes.Compare(buf, prv)
if cmp != 0 {
err = printLine(i, buf, out)
if err != nil {
return err
}
} else if prevCmp != 0 {
_, err = out.Write([]byte("*\n"))
if err != nil {
return err
}
}
prevCmp = cmp
tmp := prv
prv = buf
buf = tmp
if n < 16 {
_, err = fmt.Fprintf(out, "%08x\n", i+n)
return err
}
}
}
func main() {
f := bufio.NewWriter(os.Stdout)
defer f.Flush()
err := run(os.Args[1:], f)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}