-
Notifications
You must be signed in to change notification settings - Fork 15
/
chan_future.go
87 lines (73 loc) · 2.33 KB
/
chan_future.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
package redis
// ChanFutured wraps Sender and provides asynchronous interface through future implemented
// with channel.
type ChanFutured struct {
S Sender
}
// Send sends requests and returns ChanFuture for result.
func (s ChanFutured) Send(r Request) *ChanFuture {
f := &ChanFuture{wait: make(chan struct{})}
s.S.Send(r, f, 0)
return f
}
// SendMany sends several requests and returns slice of ChanFuture for results.
func (s ChanFutured) SendMany(reqs []Request) ChanFutures {
futures := make(ChanFutures, len(reqs))
for i := range futures {
futures[i] = &ChanFuture{wait: make(chan struct{})}
}
s.S.SendMany(reqs, futures, 0)
return futures
}
// SendTransaction sends several requests as MULTI+EXEC transaction,
// returns ChanTransaction - wrapper around ChanFuture with additional method.
func (s ChanFutured) SendTransaction(r []Request) *ChanTransaction {
future := &ChanTransaction{
ChanFuture: ChanFuture{wait: make(chan struct{})},
}
s.S.SendTransaction(r, future, 0)
return future
}
// ChanFuture - future implemented with channel as signal of fulfillment.
type ChanFuture struct {
r interface{}
wait chan struct{}
}
// Value waits for result to be fulfilled and returns result.
func (f *ChanFuture) Value() interface{} {
<-f.wait
return f.r
}
// Done returns channel that will be closed on fulfillment.
func (f *ChanFuture) Done() <-chan struct{} {
return f.wait
}
// Resolve - implementation of Future.Resolve
func (f *ChanFuture) Resolve(res interface{}, _ uint64) {
f.r = res
close(f.wait)
}
// Cancelled - implementation of Future.Cancelled (always false).
func (f *ChanFuture) Cancelled() error {
return nil
}
// ChanFutures - implementation of Future over slice of *ChanFuture
type ChanFutures []*ChanFuture
// Cancelled - implementation of Future.Cancelled (always false).
func (f ChanFutures) Cancelled() error {
return nil
}
// Resolve - implementation of Future.Resolve.
// It resolves ChanFuture corresponding to index.
func (f ChanFutures) Resolve(res interface{}, i uint64) {
f[i].Resolve(res, i)
}
// ChanTransaction - wrapper over ChanFuture with additional convenient method.
type ChanTransaction struct {
ChanFuture
}
// Results - parses result of transaction and returns it as an array of results.
func (f *ChanTransaction) Results() ([]interface{}, error) {
<-f.wait
return TransactionResponse(f.r)
}