-
Notifications
You must be signed in to change notification settings - Fork 2
/
map.go
92 lines (81 loc) · 2.1 KB
/
map.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
package gstream
import "context"
// MapFunction represents a Map transformation function.
type MapFunction[T, R any] func(context.Context, T) (R, error)
// Map takes one element and produces one element.
//
// in -- 1 -- 2 ---- 3 -- 4 ------ 5 --
//
// [ ---------- MapFunction ---------- ]
//
// out -- 1' - 2' --- 3' - 4' ----- 5' -
type Map[T, R any] struct {
FlowState
mapFunction MapFunction[T, R]
in chan interface{}
out chan interface{}
parallelism uint
}
// Verify Map satisfies the Transfer interface.
var _ Transfer = (*Map[any, any])(nil)
// NewMap returns a new Map instance.
//
// mapFunction is the Map transformation function.
// parallelism is the flow parallelism factor. In case the events order matters, use parallelism = 1.
func NewMap[T, R any](mapFunction MapFunction[T, R], parallelism ...uint) *Map[T, R] {
mapFlow := &Map[T, R]{
mapFunction: mapFunction,
in: make(chan interface{}),
out: make(chan interface{}),
parallelism: parallel(parallelism),
}
go mapFlow.doStream()
return mapFlow
}
// Via streams data through the given flow
func (m *Map[T, R]) Via(flow Transfer) Transfer {
flow.setState(m.State())
go m.transmit(flow)
return flow
}
// To streams data to the given sink
func (m *Map[T, R]) To(sink Sink) {
sink.setSinkState(m.State())
go m.transmit(sink)
}
// Out returns an output channel for sending data
func (m *Map[T, R]) Out() <-chan interface{} {
return m.out
}
// In returns an input channel for receiving data
func (m *Map[T, R]) In() chan<- interface{} {
return m.in
}
func (m *Map[T, R]) transmit(inlet Inlet) {
for element := range m.Out() {
inlet.In() <- element
}
close(inlet.In())
}
func (m *Map[T, R]) doStream() {
sem := make(chan struct{}, m.parallelism)
for elem := range m.in {
sem <- struct{}{}
go func(element T) {
defer func() { <-sem }()
if m.HasStateErr() {
return
}
result, err := m.mapFunction(m.Context(), element)
if err != nil {
m.SetStateErr(err)
return
}
m.out <- result
}(elem.(T))
}
for i := 0; i < int(m.parallelism); i++ {
sem <- struct{}{}
}
close(m.out)
}