-
Notifications
You must be signed in to change notification settings - Fork 1
/
writehasher.go
63 lines (55 loc) · 1.31 KB
/
writehasher.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
package main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"hash"
"io"
)
// WriteHasher counts writes to a io.writer, used to assess the size of a file
// without needing to store it
type WriteHasher struct {
backing io.Writer
count int64
md5er hash.Hash
sha1er hash.Hash
sha256er hash.Hash
}
// Write writes some bytes to the hasher and the backing
// writer
func (w *WriteHasher) Write(p []byte) (n int, err error) {
n, err = w.backing.Write(p)
w.md5er.Write(p)
w.sha1er.Write(p)
w.sha256er.Write(p)
w.count += int64(n)
return
}
// Count returns the number of hytes in total that have
// been written to the writer
func (w *WriteHasher) Count() int64 {
return w.count
}
// MD5Sum of the input so far
func (w *WriteHasher) MD5Sum() []byte {
return w.md5er.Sum(nil)
}
// SHA1Sum of the input so far
func (w *WriteHasher) SHA1Sum() []byte {
return w.sha1er.Sum(nil)
}
// SHA256Sum of the input so far
func (w *WriteHasher) SHA256Sum() []byte {
return w.sha256er.Sum(nil)
}
// MakeWriteHasher creates an io.Writer to calculate the sha1,sha256 and
// md5 sums and measure the size of a data written to the passed writer
func MakeWriteHasher(w io.Writer) *WriteHasher {
return &WriteHasher{
backing: w,
count: 0,
md5er: md5.New(),
sha1er: sha1.New(),
sha256er: sha256.New(),
}
}