-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgobin2hex.go
78 lines (70 loc) · 1.35 KB
/
gobin2hex.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
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"go/token"
"log"
"os"
"unicode"
)
func main() {
log.SetFlags(0)
log.SetPrefix("gobin2hex: ")
flag.Usage = usage
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
}
name := flag.Arg(0)
if !isIdent(name) {
log.Fatalf("invalid identifier %q", name)
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "// automatically generated by gobin2hex\n")
fmt.Fprintf(buf, "var %s = []uint8{\n\t", name)
i := uint64(0)
for {
var b [8192]byte
n, err := os.Stdin.Read(b[:])
for j := 0; j < n; j++ {
if i != 0 && i%10 == 0 {
fmt.Fprintf(buf, "\n\t")
}
i++
fmt.Fprintf(buf, "%#02x,", b[j])
}
if err != nil {
break
}
}
fmt.Fprintf(buf, "\n}")
src, err := format.Source(buf.Bytes())
if err != nil {
fmt.Printf("Source:\n%s\n", buf.Bytes())
fmt.Printf("\n")
panic(err)
}
fmt.Printf("%s\n", src)
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: firmware")
flag.PrintDefaults()
os.Exit(2)
}
func isIdent(ident string) bool {
tok := token.Lookup(ident)
if tok != token.IDENT {
return false
}
for i, ch := range ident {
switch {
case i == 0 && !unicode.IsLetter(ch):
return false
case i > 0 && !(unicode.IsLetter(ch) || unicode.IsNumber(ch) || ch == '_'):
return false
}
}
return true
}