2023-10-09 17:36:04 +08:00
|
|
|
|
package ecs
|
|
|
|
|
|
2023-10-12 14:04:23 +08:00
|
|
|
|
// 结果
|
|
|
|
|
type Result[T any] struct {
|
|
|
|
|
Val T
|
|
|
|
|
Err error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type EmptyType struct{}
|
|
|
|
|
|
|
|
|
|
// 新建一个OK空结果
|
|
|
|
|
func NewOkEmptyResult() Result[EmptyType] {
|
|
|
|
|
return Result[EmptyType]{Val: struct{}{}, Err: nil}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 新建一个OK结果
|
|
|
|
|
func NewOkResult[T any](val T) Result[T] {
|
|
|
|
|
return Result[T]{Val: val, Err: nil}
|
|
|
|
|
}
|
|
|
|
|
|
2023-11-07 13:22:31 +08:00
|
|
|
|
func NewResult[T any](val T, err error) Result[T] {
|
|
|
|
|
return Result[T]{Val: val, Err: err}
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-12 14:04:23 +08:00
|
|
|
|
// 新建一个错误结果
|
|
|
|
|
func NewErrResult(err error) Result[EmptyType] {
|
|
|
|
|
return Result[EmptyType]{Val: struct{}{}, Err: err}
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-09 17:36:04 +08:00
|
|
|
|
// 请求世界执行给定函数
|
2023-10-12 14:04:23 +08:00
|
|
|
|
func Request[T any](w World, handler func() Result[T]) chan Result[T] {
|
|
|
|
|
future := make(chan Result[T])
|
2023-11-06 09:25:54 +08:00
|
|
|
|
err := w.Execute(func() {
|
2023-10-12 14:04:23 +08:00
|
|
|
|
result := handler()
|
2023-10-09 17:36:04 +08:00
|
|
|
|
select {
|
2023-10-12 14:04:23 +08:00
|
|
|
|
// 即使外面不接收,也不会卡停World运行
|
|
|
|
|
case future <- result:
|
2023-10-09 17:36:04 +08:00
|
|
|
|
default:
|
|
|
|
|
}
|
|
|
|
|
})
|
2023-11-06 09:25:54 +08:00
|
|
|
|
// 世界执行错误直接响应错误
|
|
|
|
|
if err != nil {
|
|
|
|
|
go func() {
|
|
|
|
|
select {
|
|
|
|
|
case future <- Result[T]{Err: err}:
|
|
|
|
|
default:
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
}
|
2023-10-09 17:36:04 +08:00
|
|
|
|
return future
|
|
|
|
|
}
|