-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombine.go
100 lines (80 loc) · 1.64 KB
/
combine.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Copyright (c) 2024 Mikhail Knyazhev <markus621@yandex.ru>. All rights reserved.
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/
package xc
import (
"context"
"errors"
"reflect"
"time"
)
type joinedCtx struct {
main context.Context
multi []context.Context
}
func (j joinedCtx) Deadline() (deadline time.Time, has bool) {
for _, ctx := range j.multi {
dl, ok := ctx.Deadline()
if !ok {
continue
}
if !has {
deadline, has = dl, true
continue
}
if dl.Before(deadline) {
deadline = dl
}
}
return deadline, has
}
func (j joinedCtx) Done() <-chan struct{} {
return j.main.Done()
}
func (j joinedCtx) Err() (err error) {
for _, ctx := range j.multi {
err = errors.Join(err, ctx.Err())
}
return
}
func (j joinedCtx) Value(key any) any {
for _, ctx := range j.multi {
if value := ctx.Value(key); value != nil {
return value
}
}
return nil
}
func (joinedCtx) String() string {
return "xc.Join"
}
func Join(multi ...context.Context) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
if len(multi) == 0 {
return ctx, cancel
}
multi = append(multi, ctx)
jCtx := joinedCtx{
main: ctx,
multi: multi,
}
startC := make(chan struct{}, 1)
go func() {
cases := make([]reflect.SelectCase, 0, len(multi))
for _, vv := range multi {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(vv.Done()),
})
}
close(startC)
chosen, _, _ := reflect.Select(cases)
switch chosen {
default:
cancel()
}
}()
<-startC
return jCtx, cancel
}