state.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package state
  2. import (
  3. "fmt"
  4. "reflect"
  5. "sync"
  6. "github.com/google/uuid"
  7. )
  8. type State struct {
  9. id string
  10. data sync.Map
  11. }
  12. func New() *State {
  13. return &State{
  14. id: uuid.NewString(),
  15. }
  16. }
  17. func (s *State) Symbols() map[string]map[string]reflect.Value {
  18. return map[string]map[string]reflect.Value{
  19. "git.bazzel.dev/bmallen/helios/state/state": {
  20. "Get": reflect.ValueOf(s.Get),
  21. "Set": reflect.ValueOf(s.Set),
  22. "Delete": reflect.ValueOf(s.Delete),
  23. "Range": reflect.ValueOf(s.Range),
  24. "Keys": reflect.ValueOf(s.Keys),
  25. "ID": reflect.ValueOf(s.ID),
  26. },
  27. }
  28. }
  29. func (s *State) Get(key string) any {
  30. value, _ := s.data.Load(key)
  31. return value
  32. }
  33. func (s *State) Set(key string, value any) {
  34. s.data.Store(key, value)
  35. }
  36. func (s *State) Delete(key string) {
  37. s.data.Delete(key)
  38. }
  39. func (s *State) Range(f func(key string, value any) bool) {
  40. wf := func(key any, value any) bool {
  41. return f(fmt.Sprintf("%v", key), value)
  42. }
  43. s.data.Range(wf)
  44. }
  45. func (s *State) Keys() []string {
  46. keys := []string{}
  47. s.data.Range(func(key, value any) bool {
  48. keys = append(keys, fmt.Sprintf("%v", key))
  49. return true
  50. })
  51. return keys
  52. }
  53. func (s *State) ID() string {
  54. return s.id
  55. }