-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (70 loc) · 1.4 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"os"
"kastelo.dev/hexii"
)
var h2 bool
func main() {
log.SetFlags(0)
skip := flag.Int64("skip", 0, "Skip bytes at start")
lim := flag.Int64("lim", 0, "Limit read bytes")
flag.BoolVar(&h2, "h2", false, "Use HexII output")
flag.Usage = usage
flag.Parse()
var r io.Reader
if n := flag.NArg(); n == 0 || n == 1 && flag.Arg(0) == "-" {
// stdin
r = os.Stdin
} else if flag.NArg() == 1 {
f, err := os.Open(flag.Arg(0))
if err != nil {
log.Fatal(err)
}
defer f.Close()
r = f
} else {
usage()
os.Exit(2) // same as flag package when there are invalid flags
}
// If a skip was set, seek ahead that many bytes
if *skip != 0 {
rs := r.(io.ReadSeeker) // both files and stdin are seekable
n, err := rs.Seek(*skip, os.SEEK_SET)
if err != nil {
log.Fatal(err)
}
if n != *skip {
log.Fatalf("Skipped %d != %d", n, *skip)
}
}
// If a limit was set, stop reading after that many bytes
if *lim != 0 {
r = io.LimitReader(r, *lim)
}
dumpReader(r)
}
func dumpReader(r io.Reader) {
var d io.WriteCloser
if h2 {
d = hexii.Dumper(os.Stdout, 16, 4, true)
} else {
d = hex.Dumper(os.Stdout)
}
_, err := io.Copy(d, r)
if err != nil {
log.Fatal(err)
}
err = d.Close()
if err != nil {
log.Fatal(err)
}
}
func usage() {
fmt.Printf("Usage:\n hd [options] [filename]\n\nOptions:\n")
flag.PrintDefaults()
}