-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.go
60 lines (52 loc) · 1.32 KB
/
process.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
package concurrent
import (
"errors"
)
type processFunc func(interface{}) (interface{}, error)
const (
NillInputErr = "input cant be nill"
NillProcessFuncErr = "process func cant be nill"
ZeroLimitErr = "limit must be greater than 0"
)
func Process(input <-chan interface{}, process processFunc, limit int) ([]interface{}, error) {
if err := validate(input, process, limit); err != nil {
return nil, err
}
mux := newMux(limit, true, process)
go mux.fanOut(input)
mux.waitAll()
if err := mux.errors(); err != nil {
return nil, err
}
return mux.fanIn(), nil
}
func ProcessSlice(input []interface{}, process processFunc, limit int) ([]interface{}, error) {
if err := validate(input, process, limit); err != nil {
return nil, err
}
mux := newMux(limit, true, process)
go fanOutSlice(mux, input)
mux.waitAll()
if err := mux.errors(); err != nil {
return nil, err
}
return mux.fanIn(), nil
}
func validate(input interface{}, process processFunc, limit int) error {
if input == nil {
return errors.New(NillInputErr)
}
if process == nil {
return errors.New(NillProcessFuncErr)
}
if limit <= 0 {
return errors.New(ZeroLimitErr)
}
return nil
}
func fanOutSlice(mux *mux, input []interface{}) {
for i, v := range input {
mux.getWorker().add(&item{value: v, index: i})
}
mux.closeAllInputChannels()
}