forked from bborbe/collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel-fn-map.go
49 lines (44 loc) · 988 Bytes
/
channel-fn-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
// Copyright (c) 2023 Benjamin Borbe All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package collection
import (
"context"
"runtime"
"github.com/bborbe/errors"
"github.com/bborbe/run"
)
func ChannelFnMap[T interface{}](
ctx context.Context,
getFn func(ctx context.Context, ch chan<- T) error,
mapFn func(ctx context.Context, t T) error,
) error {
var err error
ch := make(chan T, runtime.NumCPU())
err = run.CancelOnFirstErrorWait(
ctx,
func(ctx context.Context) error {
defer close(ch)
return getFn(ctx, ch)
},
func(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case t, ok := <-ch:
if !ok {
return nil
}
if err := mapFn(ctx, t); err != nil {
return errors.Wrapf(ctx, err, "map failed")
}
}
}
},
)
if err != nil {
return errors.Wrapf(ctx, err, "map channel failed")
}
return nil
}