1 // Lightweight implementation of io.ReadCloser that checks the contents read
2 // from the underlying io.Reader a against checksum hash. To avoid reading the
3 // entire contents into a buffer up front, the hash is updated with each read,
4 // and the actual checksum is not checked until the underlying reader returns
15 var BadChecksum = errors.New("Reader failed checksum")
17 type HashCheckingReader struct {
18 // The underlying data source
21 // The hashing function to use
24 // The hash value to check against. Must be a hex-encoded lowercase string.
28 // Read from the underlying reader, update the hashing function, and pass the
29 // results through. Will return BadChecksum on the last read instead of EOF if
30 // the checksum doesn't match.
31 func (this HashCheckingReader) Read(p []byte) (n int, err error) {
32 n, err = this.Reader.Read(p)
34 this.Hash.Write(p[:n])
35 } else if err == io.EOF {
36 sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
37 if fmt.Sprintf("%x", sum) != this.Check {
44 // Write entire contents of this.Reader to 'dest'. Returns BadChecksum if the
45 // data written to 'dest' doesn't match the hash code of this.Check.
46 func (this HashCheckingReader) WriteTo(dest io.Writer) (written int64, err error) {
47 if writeto, ok := this.Reader.(io.WriterTo); ok {
48 written, err = writeto.WriteTo(io.MultiWriter(dest, this.Hash))
50 written, err = io.Copy(io.MultiWriter(dest, this.Hash), this.Reader)
53 sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
55 if fmt.Sprintf("%x", sum) != this.Check {
62 // Close() the underlying Reader if it is castable to io.ReadCloser. This will
63 // drain the underlying reader of any remaining data and check the checksum.
64 func (this HashCheckingReader) Close() (err error) {
65 _, err = io.Copy(this.Hash, this.Reader)
67 if closer, ok := this.Reader.(io.ReadCloser); ok {
71 sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
72 if fmt.Sprintf("%x", sum) != this.Check {