Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memoize file hashes #7

Merged
merged 1 commit into from
Aug 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions rules/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/gob"
"io"
"io/fs"
"log"
"net/url"
"os"
"path/filepath"
Expand All @@ -14,6 +15,13 @@ import (
"github.com/segmentio/fasthash/fnv1a"
)

type memoizedHash struct {
hash uint64
mtime time.Time
}

var hashCache = make(map[string]memoizedHash)

func hashSlice(s []string) uint64 {
return fnv1a.HashString64(strings.Join(s, ""))
}
Expand All @@ -22,7 +30,31 @@ func hashSliceAndString(s []string, str string) uint64 {
return fnv1a.HashString64(strings.Join(s, "") + str)
}

func modifiedTime(path string) time.Time {
var mtime time.Time
filepath.WalkDir(path, func(path string, info fs.DirEntry, err error) error {
if !info.IsDir() {
info, _ := info.Info()
ftime := info.ModTime()
if ftime.After(mtime) {
mtime = ftime
}
}
return nil
})
return mtime
}

func hashFile(path string) uint64 {
mtime := modifiedTime(path)
cached, hit := hashCache[path]
if hit {
if mtime == cached.mtime {
log.Println("using cached hash for", path)
return cached.hash
}
}
log.Println("computing hash for", path)
var hash uint64
filepath.WalkDir(path, func(path string, info fs.DirEntry, err error) error {
if !info.IsDir() {
Expand All @@ -32,6 +64,10 @@ func hashFile(path string) uint64 {
}
return nil
})
hashCache[path] = memoizedHash{
hash,
mtime,
}
return hash
}

Expand Down
Loading