Use values instead of pointers and use io.MultiWriter instead of homegrown impl.

This commit is contained in:
Andrey Smirnov
2014-02-03 17:39:49 +04:00
parent 0dd44f98b8
commit 08123ef5e3

View File

@@ -19,32 +19,23 @@ type ChecksumInfo struct {
}
// ChecksumsForFile generates size, MD5, SHA1 & SHA256 checksums for given file
func ChecksumsForFile(path string) (*ChecksumInfo, error) {
func ChecksumsForFile(path string) (ChecksumInfo, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
return ChecksumInfo{}, err
}
defer file.Close()
w := NewChecksumWriter(&DevNull{})
w := NewChecksumWriter()
_, err = io.Copy(w, file)
if err != nil {
return nil, err
return ChecksumInfo{}, err
}
return w.Sum(), nil
}
// DevNull just accepts anything
type DevNull struct {
}
// Write to DevNull always succeeds
func (d *DevNull) Write(p []byte) (n int, err error) {
return len(p), nil
}
// ChecksumWriter is a writer that does checksum calculation on the fly passing data
// to real writer
type ChecksumWriter struct {
@@ -59,34 +50,28 @@ var (
)
// NewChecksumWriter creates checksum calculator for given writer w
func NewChecksumWriter(w io.Writer) *ChecksumWriter {
func NewChecksumWriter() *ChecksumWriter {
return &ChecksumWriter{
w: w,
hashes: []hash.Hash{md5.New(), sha1.New(), sha256.New()},
}
}
// Write implememnts pass-through writing with checksum calculation on the fly
func (c *ChecksumWriter) Write(p []byte) (n int, err error) {
n, err = c.w.Write(p)
if err != nil {
return n, err
}
c.sum.Size += int64(n)
c.sum.Size += int64(len(p))
for _, h := range c.hashes {
h.Write(p[:n])
h.Write(p)
}
return
return len(p), nil
}
// Sum returns caculated ChecksumInfo
func (c *ChecksumWriter) Sum() *ChecksumInfo {
func (c *ChecksumWriter) Sum() ChecksumInfo {
c.sum.MD5 = fmt.Sprintf("%x", c.hashes[0].Sum(nil))
c.sum.SHA1 = fmt.Sprintf("%x", c.hashes[1].Sum(nil))
c.sum.SHA256 = fmt.Sprintf("%x", c.hashes[2].Sum(nil))
return &c.sum
return c.sum
}