This commit is contained in:
a 2023-06-11 09:26:55 -05:00
parent ba042cc537
commit e277164b2a
2 changed files with 25 additions and 24 deletions

View File

@ -5,39 +5,18 @@ import (
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
"sync"
"tuxpa.in/t/wm/src/copies" "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 { type Modifier[T any] struct {
Ref T Ref T
setters map[string]func(v string) error setters map[string]func(v string) error
getters map[string]func() (string, error) getters map[string]func() (string, error)
mu sync.RWMutex
} }
func NewModifier[T any](start T) *Modifier[T] { 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 // TODO: some error here
return nil return nil
} }
m.mu.Lock()
defer m.mu.Unlock()
return fn(v) return fn(v)
} }
func (m *Modifier[T]) GetString(k string) (string, error) { func (m *Modifier[T]) GetString(k string) (string, error) {
fn, ok := m.getters[k] fn, ok := m.getters[k]
if !ok { if !ok {
// TODO: some error here // TODO: some error here
return "", fmt.Errorf("config key '%s' not found", k) return "", fmt.Errorf("config key '%s' not found", k)
} }
m.mu.RLock()
defer m.mu.RUnlock()
return fn() return fn()
} }

17
src/bsp/cfg/helper.go Normal file
View File

@ -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)
}