sha3sum: remove dependency on fmt

probably silly, but it cuts the binary size down significantly
master
magical 2024-10-05 21:18:39 -07:00
parent b5d2ed36ca
commit 883cbd827a
1 changed files with 42 additions and 7 deletions

View File

@ -1,33 +1,68 @@
package main package main
import ( import (
"flag"
"fmt"
"io" "io"
"os" "os"
"github.com/magical/keccak" "github.com/magical/keccak"
) )
const usage = "usage: sha3sum [-h] files..."
var (
stdout = os.Stdout
stderr = os.Stderr
)
func main() { func main() {
flag.Parse() // Parse flags
if len(os.Args) <= 1 {
stderr.WriteString(usage + "\n")
return
}
args := os.Args[1:]
for _, a := range args {
switch a {
case "-h", "--help":
stdout.WriteString(usage + "\n")
return
case "", "-":
default:
if a[0] == '-' {
stderr.WriteString("sha3sum: unrecognized flag " + a + "\n")
os.Exit(1)
}
}
}
// compute file hashes
var sum [keccak.Size]byte var sum [keccak.Size]byte
h := keccak.New256() h := keccak.New256()
files := flag.Args() files := args
for _, filename := range files { for _, filename := range files {
f, err := os.Open(filename) f, err := os.Open(filename)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err) stderr.WriteString("sha3sum: " + err.Error() + "\n")
continue continue
} }
h.Reset() h.Reset()
_, err = io.Copy(h, f) _, err = io.Copy(h, f)
f.Close() f.Close()
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err) stderr.WriteString("sha3sum: " + err.Error() + "\n")
continue continue
} }
h.Sum(sum[:0]) h.Sum(sum[:0])
fmt.Printf("%x %s\n", sum, filename) stdout.WriteString(toHex(sum[:]) + " " + filename + "\n")
} }
} }
func toHex(data []byte) string {
const digits = "0123456789abcdef"
out := make([]byte, len(data)*2)
for i, v := range data {
out[i*2] = digits[v>>4]
out[i*2+1] = digits[v&15]
}
return string(out)
}