aboutsummaryrefslogtreecommitdiff
path: root/pipe/pipe.go
blob: 2ca1f8bf5ffff18680ced95395bd3c1b00b9b12f (plain)
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
package pipe

import (
	"sync"
)

func Proc[T any, V any](cin <-chan T, count int, proc func(T) V) <-chan V {
	cout := make(chan V)
	var wg sync.WaitGroup

	for i := 0; i < count; i++ {
		wg.Add(1)
		go func(<-chan T, chan<- V) {
			for i := range cin {
				cout <- proc(i)
			}
			wg.Done()
		}(cin, cout)
	}

	go func() {
		wg.Wait()
		close(cout)
	}()

	return cout
}

func noop[T any](_ T) {}

func Wait[T any](cin <-chan T) {
	for v := range cin {
		noop(v)
	}
}

func TailProc[T any](cin <-chan T, count int, proc func(T)) {
	var wg sync.WaitGroup

	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func(<-chan T) {
			for i := range cin {
				proc(i)
			}
			wg.Done()

		}(cin)
	}
	wg.Wait()
}

func Yield[T any](in []T) <-chan T {
	cout := make(chan T)

	go func(chan<- T) {
		for _, a := range in {
			cout <- a
		}
		close(cout)
	}(cout)

	return cout
}