elvish/pkg/eval/vars/callback.go

39 lines
679 B
Go
Raw Normal View History

2018-02-15 16:59:49 +08:00
package vars
2021-05-02 07:22:28 +08:00
import (
"src.elv.sh/pkg/eval/errs"
)
2018-01-05 06:42:34 +08:00
type callback struct {
set func(any) error
get func() any
2018-01-05 06:42:34 +08:00
}
2018-03-08 21:20:31 +08:00
// FromSetGet makes a variable from a set callback and a get callback.
func FromSetGet(set func(any) error, get func() any) Var {
return &callback{set, get}
2018-01-05 06:42:34 +08:00
}
func (cv *callback) Set(val any) error {
2018-01-05 06:42:34 +08:00
return cv.set(val)
}
func (cv *callback) Get() any {
2018-01-05 06:42:34 +08:00
return cv.get()
}
type roCallback func() any
2018-01-05 06:42:34 +08:00
2018-03-08 21:20:31 +08:00
// FromGet makes a variable from a get callback. The variable is read-only.
func FromGet(get func() any) Var {
return roCallback(get)
2018-01-05 06:42:34 +08:00
}
func (cv roCallback) Set(any) error {
return errs.SetReadOnlyVar{}
2018-01-05 06:42:34 +08:00
}
func (cv roCallback) Get() any {
2018-01-05 06:42:34 +08:00
return cv()
}