65 lines
1.1 KiB
Go
65 lines
1.1 KiB
Go
|
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() {
|
||
|
ticker := time.NewTicker(10 * time.Second)
|
||
|
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
|
||
|
}
|