mirror of
1
Fork 0
gotosocial/vendor/codeberg.org/gruf/go-runners/context.go

65 lines
1.1 KiB
Go
Raw Normal View History

2022-01-03 17:37:09 +01:00
package runners
import (
"context"
"time"
)
// closedctx is an always closed context.
var closedctx = func() context.Context {
ctx := make(chan struct{})
close(ctx)
return CancelCtx(ctx)
}()
// Closed returns an always closed context.
func Closed() context.Context {
return closedctx
}
// CtxWithCancel returns a new context.Context impl with cancel.
func CtxWithCancel() (context.Context, context.CancelFunc) {
ctx := make(chan struct{})
cncl := func() { close(ctx) }
return CancelCtx(ctx), cncl
2022-01-03 17:37:09 +01:00
}
// CancelCtx is the simplest possible cancellable context.
type CancelCtx (<-chan struct{})
2022-01-03 17:37:09 +01:00
func (CancelCtx) Deadline() (time.Time, bool) {
2022-01-03 17:37:09 +01:00
return time.Time{}, false
}
func (ctx CancelCtx) Done() <-chan struct{} {
2022-01-03 17:37:09 +01:00
return ctx
}
func (ctx CancelCtx) Err() error {
2022-01-03 17:37:09 +01:00
select {
case <-ctx:
return context.Canceled
default:
return nil
}
}
func (CancelCtx) Value(key interface{}) interface{} {
2022-01-03 17:37:09 +01:00
return nil
}
func (ctx CancelCtx) String() string {
var state string
select {
case <-ctx:
state = "closed"
default:
state = "open"
}
return "CancelCtx{state:" + state + "}"
}
func (ctx CancelCtx) GoString() string {
return "runners." + ctx.String()
}