-
Notifications
You must be signed in to change notification settings - Fork 0
/
iohash.go
58 lines (47 loc) · 1.03 KB
/
iohash.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
package iohash
import (
"fmt"
"hash"
"io"
)
// FIXME hash implements io.Writer and can be used with io.MultiWriter
// so is this module obsolete ?
func StringOfHash(h hash.Hash) string {
return fmt.Sprintf("%x", h.Sum(nil))
}
type HashWriter struct {
io.Writer
hash.Hash
}
func (h HashWriter) String() string {
return StringOfHash(h.Hash)
}
func (h *HashWriter) Write(p []byte) (n int, err error) {
n, err = h.Writer.Write(p)
if err == nil {
// Hash.Write never returns an error (see godoc interface definition)
h.Hash.Write(p[:n])
}
return
}
func NewWriter(w io.Writer, h hash.Hash) *HashWriter {
return &HashWriter{w, h}
}
type HashReader struct {
io.Reader
hash.Hash
}
func (h HashReader) String() string {
return StringOfHash(h.Hash)
}
func (h *HashReader) Read(p []byte) (int, error) {
n, err := h.Reader.Read(p)
if n > 0 {
// Hash.Write never returns an error (see godoc interface definition)
h.Hash.Write(p[:n])
}
return n, err
}
func NewReader(r io.Reader, h hash.Hash) *HashReader {
return &HashReader{r, h}
}