6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-06-28 17:51:04 +00:00
prologic-saltyim/state.go
James Mills 6a92c9d30a Add support for indexing and persisting inbox index state (#121)
TODO:

- [ ] Remove `replace` directive after testing...

Co-authored-by: James Mills <prologic@shortcircuit.net.au>
Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/121
2022-04-02 14:15:46 +00:00

82 lines
1.3 KiB
Go

package saltyim
import (
"encoding/json"
"fmt"
"io"
"os"
sync "github.com/sasha-s/go-deadlock"
)
// DefaultState returns a default state file
func DefaultState() string {
return os.ExpandEnv("$HOME/.config/salty/state.json")
}
type State struct {
sync.RWMutex
Indicies map[string]int
}
func NewState() *State {
return &State{
Indicies: make(map[string]int),
}
}
func (s *State) GetIndex(name string) int {
s.RLock()
defer s.RUnlock()
return s.Indicies[name]
}
func (s *State) SetIndex(name string, index int) {
s.Lock()
defer s.Unlock()
s.Indicies[name] = index
}
func (s *State) Bytes() ([]byte, error) {
s.Lock()
defer s.Unlock()
data, err := json.Marshal(s)
if err != nil {
return nil, fmt.Errorf("error encoding state: %w", err)
}
return data, nil
}
func (s *State) Save(fn string) error {
data, err := s.Bytes()
if err != nil {
return err
}
if err := os.WriteFile(fn, data, 0644); err != nil {
return fmt.Errorf("error writing state file %s: %w", fn, err)
}
return nil
}
func LoadState(r io.Reader) (*State, error) {
var state *State
data, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("error reading state: %w", err)
}
if err := json.Unmarshal(data, &state); err != nil {
return nil, fmt.Errorf("error reading state: %w", err)
}
return state, nil
}