music-library/hash_cache.go

65 lines
1.1 KiB
Go
Raw Normal View History

2025-01-15 12:48:20 +01:00
package main
import (
"crypto/sha512"
"encoding/gob"
"fmt"
"os"
"path/filepath"
"time"
"git.tordarus.net/tordarus/cmap"
)
var HashCache = cmap.New[[sha512.Size]byte, [sha512.Size]byte]()
func InitCache() {
path := os.ExpandEnv(FlagCacheFile)
file, err := os.Open(path)
if err == nil {
defer file.Close()
data := map[[sha512.Size]byte][sha512.Size]byte{}
gob.NewDecoder(file).Decode(&data)
HashCache.Do(func(m map[[64]byte][64]byte) {
for key, value := range data {
m[key] = value
}
})
}
go func() {
2025-01-15 15:22:52 +01:00
ticker := time.NewTicker(FlagUpdateCacheFileInterval)
2025-01-15 12:48:20 +01:00
defer ticker.Stop()
for range ticker.C {
if err := WriteCache(); err != nil {
fmt.Fprintln(os.Stderr, fmt.Errorf("could not write cache file: %w", err))
}
}
}()
}
func WriteCache() error {
path := os.ExpandEnv(FlagCacheFile)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
data := HashCache.Clone()
if err := gob.NewEncoder(file).Encode(data); err != nil {
return err
}
fmt.Println("hashsum cache written")
return nil
}