From 883cbd827a055ae48139288dc57c563149ae919e Mon Sep 17 00:00:00 2001 From: Andrew Ekstedt Date: Sat, 5 Oct 2024 21:18:39 -0700 Subject: [PATCH] sha3sum: remove dependency on fmt probably silly, but it cuts the binary size down significantly --- sha3sum/main.go | 49 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/sha3sum/main.go b/sha3sum/main.go index 63127a6..c5255b5 100644 --- a/sha3sum/main.go +++ b/sha3sum/main.go @@ -1,33 +1,68 @@ package main import ( - "flag" - "fmt" "io" "os" "github.com/magical/keccak" ) +const usage = "usage: sha3sum [-h] files..." + +var ( + stdout = os.Stdout + stderr = os.Stderr +) + 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 h := keccak.New256() - files := flag.Args() + files := args for _, filename := range files { f, err := os.Open(filename) if err != nil { - fmt.Fprintln(os.Stderr, err) + stderr.WriteString("sha3sum: " + err.Error() + "\n") continue } h.Reset() _, err = io.Copy(h, f) f.Close() if err != nil { - fmt.Fprintln(os.Stderr, err) + stderr.WriteString("sha3sum: " + err.Error() + "\n") continue } 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) +}