-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGenHashFile.go
100 lines (79 loc) · 1.87 KB
/
GenHashFile.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"io"
"os"
"sync"
)
//通用的一个封装类,把具体算法封装在外面,
//这样算法可以随意增加,不影响这里的逻辑
type GenHashFile struct {
FullPath string
WG *sync.WaitGroup
Coders []HashCoder
}
type FileResp struct {
FileName string
FullPath string
Hashes []*HashResp
}
type HashResp struct {
CodeName string
HashVal string
}
func (_self *GenHashFile) Generate() []*HashResp {
file, err := os.Open(_self.FullPath)
if err != nil {
panic(err.Error())
}
defer file.Close()
data := make([]byte, 4_194_304)
for {
n, err := file.Read(data)
if err != nil && err != io.EOF {
panic(err.Error())
break
}
// 需要复制一份,否则goroutines 共同对 data 对象的操作可能出现问题
tmp := make([]byte, len(data))
copy(tmp, data)
_self.WriteToChan(tmp[:n])
if err == io.EOF {
break
}
}
_self.CloseChan()
//需要先关闭通道,然后等待写入全部完成
_self.WG.Wait()
return _self.GetAllHash()
}
func (_self *GenHashFile) LoadAllCoders() {
//_self.LoadCoders(new(Md5Coder), new(SHA1Coder), new(SHA256Coder), new(SHA512Coder))
_self.LoadCoders(GetAllCoders()...)
}
func (_self *GenHashFile) LoadCoders(_coders ...HashCoder) {
_self.Coders = _coders
//
_self.WG = new(sync.WaitGroup)
for _, coder := range _self.Coders {
coder.Create()
//使用多协程同时读取
coder.ReadFromChan(_self.WG)
}
}
func (_self *GenHashFile) WriteToChan(input []byte) {
for _, coder := range _self.Coders {
coder.WriteToChan(input)
}
}
func (_self *GenHashFile) CloseChan() {
for _, coder := range _self.Coders {
coder.CloseChan()
}
}
func (_self *GenHashFile) GetAllHash() []*HashResp {
var results []*HashResp
for _, coder := range _self.Coders {
results = append(results, &HashResp{CodeName: coder.Name(), HashVal: coder.GenHashHex()})
}
return results
}