cached_values.go 754 B

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