Add concurrency.

This commit is contained in:
Greg 2020-04-02 14:06:11 -04:00
parent 341054857e
commit 8b70410d58

52
main.go
View File

@ -6,41 +6,53 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"sync"
"github.com/zeebo/blake3" "github.com/zeebo/blake3"
) )
var ( var (
help = flag.Bool("h", false, "Prints help information") help = flag.Bool("h", false, "Prints help information")
length = flag.Int("l", 32, "The number of output bytes, prior to hex encoding (default 32)") length = flag.Int("l", 32, "The number of output bytes, prior to hex encoding")
par = flag.Int("p", 4, "The maximum concurrency")
) )
func main() { func main() {
flag.Parse() flag.Parse()
if *help || len(flag.Args()) == 0 { if *help || len(flag.Args()) == 0 || *par < 1 {
flag.Usage() flag.Usage()
os.Exit(0) os.Exit(0)
} }
buf := [65536]byte{} q := make(chan struct{}, *par)
wg := &sync.WaitGroup{}
for _, name := range flag.Args() { for _, name := range flag.Args() {
file, err := os.Open(name) q <- struct{}{}
if err != nil { wg.Add(1)
panic(err) go func(name string) {
} buf := [65536]byte{}
hasher := blake3.NewSized(*length) file, err := os.Open(name)
for { if err != nil {
n, err := file.Read(buf[:])
hasher.Write(buf[:n])
if err == io.EOF {
break
} else if err != nil {
panic(err) panic(err)
} }
} hasher := blake3.NewSized(*length)
file.Close() for {
hash := hasher.Sum([]byte{}) n, err := file.Read(buf[:])
fmt.Print(hex.EncodeToString(hash)) hasher.Write(buf[:n])
fmt.Print(" ") if err == io.EOF {
fmt.Println(name) break
} else if err != nil {
panic(err)
}
}
file.Close()
hash := hasher.Sum([]byte{})
fmt.Print(hex.EncodeToString(hash))
fmt.Print(" ")
fmt.Println(name)
<- q
wg.Done()
}(name)
} }
wg.Wait()
} }