Debian Codegraph @

internal/cancelctx/context.go

raw
1 package cancelctx
2
3 import (
4 "context"
5 "time"
6 )
7
8 // customCancelContext wraps context and cancels as soon as channel closed.
9 type customCancelContext struct {
10 context.Context
11 ch <-chan struct{}
12 }
13
14 // Deadline not used.
15 func (c customCancelContext) Deadline() (time.Time, bool) { return time.Time{}, false }
16
17 // Done returns channel that will be closed as soon as connection closed.
18 func (c customCancelContext) Done() <-chan struct{} { return c.ch }
19
20 // Err returns context error.
21 func (c customCancelContext) Err() error {
22 select {
23 case <-c.ch:
24 return context.Canceled
25 default:
26 return nil
27 }
28 }
29
30 // New returns a wrapper context around original context that will
31 // be canceled on channel close.
32 func New(ctx context.Context, ch <-chan struct{}) context.Context {
33 return customCancelContext{Context: ctx, ch: ch}
34 }