10 var BadChecksum = errors.New("Reader failed checksum")
12 // HashCheckingReader is an io.ReadCloser that checks the contents
13 // read from the underlying io.Reader against the provided hash.
14 type HashCheckingReader struct {
15 // The underlying data source
18 // The hash function to use
21 // The hash value to check against. Must be a hex-encoded lowercase string.
25 // Reads from the underlying reader, update the hashing function, and
26 // pass the results through. Returns BadChecksum (instead of EOF) on
27 // the last read if the checksum doesn't match.
28 func (this HashCheckingReader) Read(p []byte) (n int, err error) {
29 n, err = this.Reader.Read(p)
31 this.Hash.Write(p[:n])
34 sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
35 if fmt.Sprintf("%x", sum) != this.Check {
42 // WriteTo writes the entire contents of this.Reader to dest. Returns
43 // BadChecksum if the checksum doesn't match.
44 func (this HashCheckingReader) WriteTo(dest io.Writer) (written int64, err error) {
45 if writeto, ok := this.Reader.(io.WriterTo); ok {
46 written, err = writeto.WriteTo(io.MultiWriter(dest, this.Hash))
48 written, err = io.Copy(io.MultiWriter(dest, this.Hash), this.Reader)
51 sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
53 if fmt.Sprintf("%x", sum) != this.Check {
60 // Close reads all remaining data from the underlying Reader and
61 // returns BadChecksum if the checksum doesn't match. It also closes
62 // the underlying Reader if it implements io.ReadCloser.
63 func (this HashCheckingReader) Close() (err error) {
64 _, err = io.Copy(this.Hash, this.Reader)
66 if closer, ok := this.Reader.(io.Closer); ok {
67 err2 := closer.Close()
68 if err2 != nil && err == nil {
76 sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
77 if fmt.Sprintf("%x", sum) != this.Check {