-
Notifications
You must be signed in to change notification settings - Fork 2
/
async.go
68 lines (57 loc) · 940 Bytes
/
async.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
package fx
import "sync"
func makeAsync(it Iterator, bs uint) Iterator {
s := &async{
it: it,
ch: make(chan result, bs),
closeCh: make(chan struct{}),
wg: sync.WaitGroup{},
}
s.start()
return s
}
type async struct {
it Iterator
ch chan result
closeCh chan struct{}
wg sync.WaitGroup
}
func (s *async) start() {
s.wg.Add(1)
go func() {
defer func() {
s.wg.Done()
close(s.ch)
}()
consumeIter(s.it, s.ch, s.closeCh)
}()
}
func (s *async) Next() (Any, error) {
r, has := <-s.ch
if !has {
return nil, errNone
}
return r.v, r.err
}
func (s *async) Close() {
close(s.closeCh)
s.wg.Wait()
s.it.Close()
}
func consumeIter(it Iterator, ch chan<- result, closeCh <-chan struct{}) {
loop:
for {
v, err := it.Next()
if err != nil && IsNone(err) {
break loop
}
select {
case <-closeCh:
break loop
case ch <- result{
v: v,
err: err,
}:
}
}
}