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 f66b505d1a Fix GetState() (#129)
Should return `-1` if no state is found.

Co-authored-by: James Mills <prologic@shortcircuit.net.au>
Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/129
2022-04-02 22:27:05 +00:00

86 lines
1.4 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()
index, ok := s.Indicies[name]
if !ok {
return -1 // -1 is a special value meaning start from the beginning
}
return index
}
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
}