2015-02-15 22:21:35 +00:00
|
|
|
package backend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"hash"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HashAppendWriter struct {
|
|
|
|
w io.Writer
|
|
|
|
origWr io.Writer
|
|
|
|
h hash.Hash
|
|
|
|
sum []byte
|
|
|
|
closed bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewHashAppendWriter(w io.Writer, h hash.Hash) *HashAppendWriter {
|
|
|
|
return &HashAppendWriter{
|
|
|
|
h: h,
|
|
|
|
w: io.MultiWriter(w, h),
|
|
|
|
origWr: w,
|
|
|
|
sum: make([]byte, 0, h.Size()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HashAppendWriter) Close() error {
|
2015-05-01 15:13:03 +00:00
|
|
|
if h == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-02-15 22:21:35 +00:00
|
|
|
if !h.closed {
|
|
|
|
h.closed = true
|
|
|
|
|
|
|
|
_, err := h.origWr.Write(h.h.Sum(nil))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HashAppendWriter) Write(p []byte) (n int, err error) {
|
|
|
|
if !h.closed {
|
|
|
|
return h.w.Write(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0, errors.New("Write() called on closed HashAppendWriter")
|
|
|
|
}
|
|
|
|
|
2015-11-29 13:27:52 +00:00
|
|
|
// HashingWriter wraps an io.Writer to hashes all data that is written to it.
|
2015-02-15 22:21:35 +00:00
|
|
|
type HashingWriter struct {
|
2015-02-15 23:24:43 +00:00
|
|
|
w io.Writer
|
|
|
|
h hash.Hash
|
|
|
|
size int
|
2015-02-15 22:21:35 +00:00
|
|
|
}
|
|
|
|
|
2015-11-29 13:27:52 +00:00
|
|
|
// NewHashAppendWriter wraps the writer w and feeds all data written to the hash h.
|
2015-02-15 22:21:35 +00:00
|
|
|
func NewHashingWriter(w io.Writer, h hash.Hash) *HashingWriter {
|
|
|
|
return &HashingWriter{
|
|
|
|
h: h,
|
|
|
|
w: io.MultiWriter(w, h),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-29 13:27:52 +00:00
|
|
|
// Write wraps the write method of the underlying writer and also hashes all data.
|
2015-02-15 22:21:35 +00:00
|
|
|
func (h *HashingWriter) Write(p []byte) (int, error) {
|
2015-02-15 23:24:43 +00:00
|
|
|
n, err := h.w.Write(p)
|
|
|
|
h.size += n
|
|
|
|
return n, err
|
2015-02-15 22:21:35 +00:00
|
|
|
}
|
|
|
|
|
2015-11-29 13:27:52 +00:00
|
|
|
// Sum returns the hash of all data written so far.
|
2015-02-15 22:21:35 +00:00
|
|
|
func (h *HashingWriter) Sum(d []byte) []byte {
|
|
|
|
return h.h.Sum(d)
|
|
|
|
}
|
2015-02-15 23:24:43 +00:00
|
|
|
|
2015-11-29 13:27:52 +00:00
|
|
|
// Size returns the number of bytes written to the underlying writer.
|
2015-02-15 23:24:43 +00:00
|
|
|
func (h *HashingWriter) Size() int {
|
|
|
|
return h.size
|
|
|
|
}
|