2
2
mirror of https://github.com/octoleo/restic.git synced 2024-12-29 05:13:09 +00:00
restic/internal/hashing/reader.go

52 lines
985 B
Go
Raw Normal View History

2017-01-22 11:43:36 +00:00
package hashing
import (
"hash"
"io"
)
2021-01-01 11:42:33 +00:00
// 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
2017-01-22 11:43:36 +00:00
h hash.Hash
}
2021-01-01 11:42:33 +00:00
type readWriterTo struct {
reader
writerTo io.WriterTo
2017-01-22 11:43:36 +00:00
}
2021-01-01 11:42:33 +00:00
// 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
2017-01-22 11:43:36 +00:00
}
// Sum returns the hash of the data read so far.
2021-01-01 11:42:33 +00:00
func (h *reader) Sum(d []byte) []byte {
2017-01-22 11:43:36 +00:00
return h.h.Sum(d)
}
2021-01-01 11:42:33 +00:00
// 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))
}