-
Notifications
You must be signed in to change notification settings - Fork 361
/
hashing_reader.go
59 lines (53 loc) · 1.09 KB
/
hashing_reader.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
package block
import (
"crypto/md5" //nolint:gosec
"crypto/sha256"
"hash"
"io"
"strconv"
)
type HashFunction int
const (
HashFunctionMD5 HashFunction = iota
HashFunctionSHA256
)
type HashingReader struct {
Md5 hash.Hash
Sha256 hash.Hash
originalReader io.Reader
CopiedSize int64
}
func (s *HashingReader) Read(p []byte) (int, error) {
nb, err := s.originalReader.Read(p)
s.CopiedSize += int64(nb)
if s.Md5 != nil {
if _, err2 := s.Md5.Write(p[0:nb]); err2 != nil {
return nb, err2
}
}
if s.Sha256 != nil {
if _, err2 := s.Sha256.Write(p[0:nb]); err2 != nil {
return nb, err2
}
}
return nb, err
}
func NewHashingReader(body io.Reader, hashTypes ...HashFunction) *HashingReader {
s := new(HashingReader)
s.originalReader = body
for _, hashType := range hashTypes {
switch hashType {
case HashFunctionMD5:
if s.Md5 == nil {
s.Md5 = md5.New() //nolint:gosec
}
case HashFunctionSHA256:
if s.Sha256 == nil {
s.Sha256 = sha256.New()
}
default:
panic("wrong hash type number " + strconv.Itoa(int(hashType)))
}
}
return s
}