saltyim is the Go library and reference client and broker implementation for Salty IM it contains a command-line client (cli), a terminal user interface (tui), builtin server/broker and a Mobile / Desktop App PWA (progressive web app) https://salty.im/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
saltyim/state.go

81 lines
1.3 KiB

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]int64
}
func NewState() *State {
return &State{
Indicies: make(map[string]int64),
}
}
func (s *State) GetIndex(name string) int64 {
s.RLock()
defer s.RUnlock()
return s.Indicies[name]
}
func (s *State) SetIndex(name string, index int64) {
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
}