gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

context.go (1177B)


      1 package runners
      2 
      3 import (
      4 	"context"
      5 	"time"
      6 )
      7 
      8 // closedctx is an always closed context.
      9 var closedctx = func() context.Context {
     10 	ctx := make(chan struct{})
     11 	close(ctx)
     12 	return CancelCtx(ctx)
     13 }()
     14 
     15 // Closed returns an always closed context.
     16 func Closed() context.Context {
     17 	return closedctx
     18 }
     19 
     20 // CtxWithCancel returns a new context.Context impl with cancel.
     21 func CtxWithCancel() (context.Context, context.CancelFunc) {
     22 	ctx := make(chan struct{})
     23 	cncl := func() { close(ctx) }
     24 	return CancelCtx(ctx), cncl
     25 }
     26 
     27 // CancelCtx is the simplest possible cancellable context.
     28 type CancelCtx (<-chan struct{})
     29 
     30 func (CancelCtx) Deadline() (time.Time, bool) {
     31 	return time.Time{}, false
     32 }
     33 
     34 func (ctx CancelCtx) Done() <-chan struct{} {
     35 	return ctx
     36 }
     37 
     38 func (ctx CancelCtx) Err() error {
     39 	select {
     40 	case <-ctx:
     41 		return context.Canceled
     42 	default:
     43 		return nil
     44 	}
     45 }
     46 
     47 func (CancelCtx) Value(key interface{}) interface{} {
     48 	return nil
     49 }
     50 
     51 func (ctx CancelCtx) String() string {
     52 	var state string
     53 	select {
     54 	case <-ctx:
     55 		state = "closed"
     56 	default:
     57 		state = "open"
     58 	}
     59 	return "CancelCtx{state:" + state + "}"
     60 }
     61 
     62 func (ctx CancelCtx) GoString() string {
     63 	return "runners." + ctx.String()
     64 }