cached_values.go 780 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. )
  10. var _ = fmt.Print
  11. type CachedValues[T any] struct {
  12. Name string
  13. Opts T
  14. }
  15. func (self *CachedValues[T]) Path() string {
  16. return filepath.Join(CacheDir(), self.Name+".json")
  17. }
  18. func (self *CachedValues[T]) Load() T {
  19. raw, err := os.ReadFile(self.Path())
  20. if err == nil {
  21. json.Unmarshal(raw, self.Opts)
  22. }
  23. return self.Opts
  24. }
  25. func (self *CachedValues[T]) Save() {
  26. raw, err := json.Marshal(self.Opts)
  27. if err == nil {
  28. AtomicUpdateFile(self.Path(), bytes.NewReader(raw), 0o600)
  29. }
  30. }
  31. func NewCachedValues[T any](name string, initial_val T) *CachedValues[T] {
  32. return &CachedValues[T]{Name: name, Opts: initial_val}
  33. }