hashing: support WriteTo in the reader

This commit is contained in:
Michael Eischer committed 2021-01-03 22:23:53 +01:00
1 parent aa0faa8c7d
commit bcb852a8d0
2 files changed
+87 -25

No files matched your search

+34 -12
View File
@@ -5,25 +5,47 @@ import (
"io"
)
// Reader hashes all data read from the underlying reader.
type Reader struct {
r io.Reader
// ReadSumer hashes all data read from the underlying reader.
type ReadSumer interface {
io.Reader
// Sum returns the hash of the data read so far.
Sum(d []byte) []byte
}
type reader struct {
io.Reader
h hash.Hash
}
// NewReader returns a new Reader that uses the hash h.
func NewReader(r io.Reader, h hash.Hash) *Reader {
return &Reader{
h: h,
r: io.TeeReader(r, h),
}
type readWriterTo struct {
reader
writerTo io.WriterTo
}
func (h *Reader) Read(p []byte) (int, error) {
return h.r.Read(p)
// NewReader returns a new ReadSummer that uses the hash h. If the underlying
// reader supports WriteTo then the returned reader will do so too.
func NewReader(r io.Reader, h hash.Hash) ReadSumer {
rs := reader{
Reader: io.TeeReader(r, h),
h: h,
}
if _, ok := r.(io.WriterTo); ok {
return &readWriterTo{
reader: rs,
writerTo: r.(io.WriterTo),
}
}
return &rs
}
// Sum returns the hash of the data read so far.
func (h *Reader) Sum(d []byte) []byte {
func (h *reader) Sum(d []byte) []byte {
return h.h.Sum(d)
}
// WriteTo reads all data into the passed writer
func (h *readWriterTo) WriteTo(w io.Writer) (int64, error) {
return h.writerTo.WriteTo(NewWriter(w, h.h))
}