diff --git a/src/bsp/cfg/cfg.go b/src/bsp/cfg/cfg.go index df847cb..c7b4c48 100644 --- a/src/bsp/cfg/cfg.go +++ b/src/bsp/cfg/cfg.go @@ -5,39 +5,18 @@ import ( "reflect" "strconv" "strings" + "sync" "tuxpa.in/t/wm/src/copies" ) -// Read will return the first non nil value or the default value -func Read[T any](xs ...*T) T { - for _, v := range xs { - if v != nil { - return *v - } - } - // zero value if all else fails - return *new(T) -} - -func ReadFunc[T any, V any](fn func(*T) *V, xs ...*T) V { - for _, v := range xs { - if v == nil { - continue - } - vv := fn(v) - if vv != nil { - return *vv - } - } - return *new(V) -} - type Modifier[T any] struct { Ref T setters map[string]func(v string) error getters map[string]func() (string, error) + + mu sync.RWMutex } func NewModifier[T any](start T) *Modifier[T] { @@ -56,14 +35,19 @@ func (m *Modifier[T]) Set(k, v string) error { // TODO: some error here return nil } + m.mu.Lock() + defer m.mu.Unlock() return fn(v) } + func (m *Modifier[T]) GetString(k string) (string, error) { fn, ok := m.getters[k] if !ok { // TODO: some error here return "", fmt.Errorf("config key '%s' not found", k) } + m.mu.RLock() + defer m.mu.RUnlock() return fn() } diff --git a/src/bsp/cfg/helper.go b/src/bsp/cfg/helper.go new file mode 100644 index 0000000..bc7ad33 --- /dev/null +++ b/src/bsp/cfg/helper.go @@ -0,0 +1,17 @@ +package cfg + +// Read from the refs of n modifiers with lock protection +func Read[T any, V any](fn func(*T) *V, xs ...*Modifier[T]) V { + for _, v := range xs { + if v == nil { + continue + } + v.mu.RLock() + vv := fn(&v.Ref) + v.mu.RUnlock() + if vv != nil { + return *vv + } + } + return *new(V) +}