- Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
64 lines (60 loc) · 1.65 KB
/
main.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
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Unhex is the opposite of hexdump -C or Plan 9's "xd -b".
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
)
// parseHexdump parses the hex dump in text, which should be the
// output of "hexdump -C" or Plan 9's "xd -b",
// and returns the original data used to produce the dump.
// It is meant to enable storing golden binary files as text, so that
// changes to the golden files can be seen during code reviews.
funcparseHexdump(textstring) ([]byte, error) {
varout []byte
for_, line:=rangestrings.Split(text, "\n") {
ifi:=strings.Index(line, "|"); i>=0 { // remove text dump
line=line[:i]
}
f:=strings.Fields(line)
iflen(f) >1+16 {
returnnil, fmt.Errorf("parsing hex dump: too many fields on line %q", line)
}
iflen(f) ==0||len(f) ==1&&f[0] =="*" { // all zeros block omitted
continue
}
addr64, err:=strconv.ParseUint(f[0], 16, 0)
iferr!=nil {
returnnil, fmt.Errorf("parsing hex dump: invalid address %q", f[0])
}
addr:=int(addr64)
iflen(out) <addr {
out=append(out, make([]byte, addr-len(out))...)
}
for_, x:=rangef[1:] {
val, err:=strconv.ParseUint(x, 16, 8)
iferr!=nil {
returnnil, fmt.Errorf("parsing hexdump: invalid hex byte %q", x)
}
out=append(out, byte(val))
}
}
returnout, nil
}
funcmain() {
hex, err:=ioutil.ReadAll(os.Stdin)
iferr!=nil {
log.Fatal(err)
}
data, err:=parseHexdump(string(hex))
iferr!=nil {
log.Fatal(err)
}
os.Stdout.Write(data)
}