-
Notifications
You must be signed in to change notification settings - Fork 5
/
xxhashdir.go
71 lines (59 loc) · 1.18 KB
/
xxhashdir.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
package xxhashdir
import (
"io"
"os"
"path/filepath"
"runtime"
"sync"
"github.com/cespare/xxhash"
)
// Entry of out chan
type Entry struct {
Path string
Xxhash uint64
}
func hashFile(path string) (uint64, error) {
var (
hash = xxhash.New()
file, err = os.Open(path)
)
if file != nil {
defer file.Close()
_, err = io.Copy(hash, file)
}
return hash.Sum64(), err
}
func produce(root string, in chan string) {
defer close(in)
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
fi, err := os.Stat(path)
if (err == nil) && (fi.Mode().IsRegular()) {
in <- path
}
return nil
})
}
func consume(in chan string, out chan Entry, wg *sync.WaitGroup) {
defer wg.Done()
for path := range in {
hash, err := hashFile(path)
if err == nil {
out <- Entry{Path: path, Xxhash: hash}
}
}
}
func stop(out chan Entry, wg *sync.WaitGroup) {
wg.Wait()
close(out)
}
// Hashdir prints all directory contents with xxhash sums
func Hashdir(root string, out chan Entry) {
in := make(chan string)
wg := &sync.WaitGroup{}
go produce(root, in)
for i := 0; i < runtime.NumCPU(); i++ {
wg.Add(1)
go consume(in, out, wg)
}
go stop(out, wg)
}