Initial commit

This commit is contained in:
Shaun Kruger
2026-10-11 21:36:20 -06:00
commit 48b6c0d6cb
13 changed files with 1717 additions and 0 deletions
+54
View File
@@ -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
}