prologic-saltyim/state.go

93 lines
1.7 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")
}
// State represents the state of a client and the indices of its inbox(es)
type State struct {
sync.RWMutex
Indicies map[string]int64
}
// NewState returns a new empty state
func NewState() *State {
return &State{
Indicies: make(map[string]int64),
}
}
// GetIndex returns the current index for the name inbox
func (s *State) GetIndex(name string) int64 {
s.RLock()
defer s.RUnlock()
return s.Indicies[name]
}
// SetIndex sets the index for the named inbox
func (s *State) SetIndex(name string, index int64) {
s.Lock()
defer s.Unlock()
s.Indicies[name] = index
}
// Bytes serialises the state into a byte slice
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
}
// Save persists the state to a file on disk
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
}
// LoadState loads a state from a file on disk
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)
}
if state.Indicies == nil {
state.Indicies = make(map[string]int64)
}
return state, nil
}