-
Notifications
You must be signed in to change notification settings - Fork 0
/
pending.go
66 lines (58 loc) · 1012 Bytes
/
pending.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
package promise
import (
"sync/atomic"
)
type PendingNoValue struct {
f *func()
v int32
state int32
}
type Pending[T any] struct {
f *func(T)
v *T
state int32
}
const (
funcSet = 1
valueSet = 2
bothSet = 3
)
func (pending *PendingNoValue) Then(f func()) {
if !cas(&pending.f, nil, &f) {
return
}
if atomic.AddInt32(&pending.state, funcSet) != bothSet {
return
}
f()
}
func (pending *PendingNoValue) Resolve() {
if !atomic.CompareAndSwapInt32(&pending.v, 0, 1) {
return
}
if atomic.AddInt32(&pending.state, valueSet) != bothSet {
return
}
pf := load(&pending.f)
(*pf)()
}
func (pending *Pending[T]) Then(f func(T)) {
if !cas(&pending.f, nil, &f) {
return
}
if atomic.AddInt32(&pending.state, funcSet) != bothSet {
return
}
pv := load(&pending.v)
f(*pv)
}
func (pending *Pending[T]) Resolve(v T) {
if !cas(&pending.v, nil, &v) {
return
}
if atomic.AddInt32(&pending.state, valueSet) != bothSet {
return
}
pf := load(&pending.f)
(*pf)(v)
}