Initial commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
fullHashLimit = 20 << 20
|
||||
sampleStride = 10 << 20
|
||||
sampleSize = 1 << 10
|
||||
)
|
||||
|
||||
// HashFile returns an MD5 hex digest. Files smaller than 20MB are hashed in full.
|
||||
// Larger files hash a 1KB sample at every 10MB offset within the whole 20MB blocks,
|
||||
// followed by the final chunk (the remainder after the last whole 20MB block).
|
||||
// If the file is an exact multiple of 20MB, the final 20MB block is used as the tail.
|
||||
func HashFile(path string, size int64) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
return hashReaderAt(f, size)
|
||||
}
|
||||
|
||||
func hashReaderAt(r io.ReaderAt, size int64) (string, error) {
|
||||
h := md5.New()
|
||||
if size < fullHashLimit {
|
||||
if _, err := io.Copy(h, io.NewSectionReader(r, 0, size)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
tailStart := size / fullHashLimit * fullHashLimit
|
||||
if tailStart == size {
|
||||
tailStart -= fullHashLimit
|
||||
}
|
||||
buf := make([]byte, sampleSize)
|
||||
for off := int64(0); off < tailStart; off += sampleStride {
|
||||
n, err := r.ReadAt(buf, off)
|
||||
if err != nil && err != io.EOF {
|
||||
return "", err
|
||||
}
|
||||
h.Write(buf[:n])
|
||||
}
|
||||
if _, err := io.Copy(h, io.NewSectionReader(r, tailStart, size-tailStart)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
Reference in New Issue
Block a user