-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtap.go
129 lines (113 loc) · 2.07 KB
/
tap.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package parallel
import (
"context"
"errors"
"io"
"sync"
)
var ErrEOD = errors.New("end of data")
type Tap[OUT any] struct {
Producer[Data[OUT]]
Runnable
out chan Data[OUT]
proc TapFunc[OUT]
wg *sync.WaitGroup
next Runnable
}
type TapFunc[OUT any] func(context.Context) (OUT, error)
func NewTap[OUT any](f TapFunc[OUT]) *Tap[OUT] {
out := make(chan Data[OUT])
return &Tap[OUT]{
out: out,
proc: f,
wg: &sync.WaitGroup{},
}
}
func (src *Tap[OUT]) Join(c Consumer[Data[OUT]]) {
c.In(src.Out())
src.next = c
}
func (src *Tap[OUT]) Out() <-chan Data[OUT] {
return src.out
}
func (src Tap[OUT]) Run(ctx context.Context) {
src.wg.Add(1)
go func() {
loop:
for {
select {
case <-ctx.Done():
break loop
default:
d, err := src.proc(ctx)
if err == ErrEOD {
break loop
}
src.out <- NewData(d, err)
}
}
src.wg.Done()
}()
go func() {
src.wg.Wait()
close(src.out)
}()
if src.next != nil {
src.next.Run(ctx)
}
}
func genFromSlice[T any](vs []T) TapFunc[T] {
var zero T
var i int
return func(context.Context) (T, error) {
if i >= len(vs) {
return zero, ErrEOD
}
v := vs[i]
i++
return v, nil
}
}
func NewTapFromSlice[T any](vs []T) *Tap[T] {
return NewTap(genFromSlice(vs))
}
type KeyValue[K comparable, V any] struct {
Key K
Value V
}
func (kv *KeyValue[K, V]) Clone() any {
if kv == nil {
return nil
}
return &KeyValue[K, V]{
Key: kv.Key,
Value: kv.Value,
}
}
func genFromMap[K comparable, V any](m map[K]V) TapFunc[*KeyValue[K, V]] {
s := make([]*KeyValue[K, V], 0, len(m))
for k, v := range m {
s = append(s, &KeyValue[K, V]{
Key: k,
Value: v,
})
}
return genFromSlice(s)
}
func NewTapFromMap[K comparable, V any](m map[K]V) *Tap[*KeyValue[K, V]] {
return NewTap(genFromMap(m))
}
type Decoder interface {
Decode(any) error
}
func NewTapFromDecoder[V any](dec Decoder) *Tap[V] {
return NewTap[V](func(ctx context.Context) (V, error) {
var v V
if err := dec.Decode(&v); err == io.EOF {
return v, ErrEOD
} else if err != nil {
return v, err
}
return v, nil
})
}