-
Notifications
You must be signed in to change notification settings - Fork 1
/
cancel-context.go
42 lines (36 loc) · 947 Bytes
/
cancel-context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
© 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package parl
import (
"context"
"github.com/haraldrudell/parl/perrors"
)
// CancelContextDo implements parl.CancelContext.
// CancelContextDo is a context with a thread-safe, race-free,
// idempotent Cancel method
type CancelContextDo struct {
context.Context
cancel context.CancelFunc
}
// NewCancelContext instantiates parl.CancelContext, a context
// with Cancel exposed as a method
func NewCancelContext(ctx context.Context) (cancelCtx CancelContext) {
c := CancelContextDo{}
c.Context, c.cancel = context.WithCancel(ctx)
return
}
// Cancel cancels this context
func (cc *CancelContextDo) Cancel() {
if cc == nil || cc.cancel == nil {
var s string
if cc == nil {
s = "context"
} else {
s = "context.cancel"
}
panic(perrors.Errorf("CancelContextDo.Cancel with %s nil", s))
}
cc.cancel()
}