helper
This commit is contained in:
parent
ba042cc537
commit
e277164b2a
@ -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()
|
||||
}
|
||||
|
||||
|
17
src/bsp/cfg/helper.go
Normal file
17
src/bsp/cfg/helper.go
Normal 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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user