-
Notifications
You must be signed in to change notification settings - Fork 6
/
ctx.go
67 lines (56 loc) · 1.24 KB
/
ctx.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// SPDX-FileCopyrightText: 2021 Henry Bubert
//
// SPDX-License-Identifier: MIT
package muxrpc
import (
"context"
"sync"
)
// withError returns a cancellable context where ctx.Err() is the passed err instead of "context cancelled"
// TODO: put this somewhere nicer
func withError(ctx context.Context, err error) (context.Context, context.CancelFunc) {
ch := make(chan struct{})
next := &closeCtx{
ch: ch,
Context: ctx,
}
var once sync.Once
cls := func() {
once.Do(func() {
next.err = err
close(ch)
})
}
go func() {
select {
case <-ctx.Done():
once.Do(func() {
next.err = ctx.Err()
close(ch)
})
case <-ch:
}
}()
return next, cls
}
// closeCtx is the context that cancels functions and returns a luigi.EOS error
type closeCtx struct {
context.Context
ch <-chan struct{}
err error
}
// Done returns a channel that is closed once the context is cancelled.
func (ctx *closeCtx) Done() <-chan struct{} {
return ctx.ch
}
// Err returns the error that made the context cancel.
// returns luigi.EOS if cancelled using our cancel function or the error
// returned by the context below if that was canceled.
func (ctx *closeCtx) Err() error {
select {
case <-ctx.ch:
return ctx.err
default:
return nil
}
}