-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchan.go
61 lines (55 loc) · 1.07 KB
/
chan.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
package goneric
import (
"time"
)
// ChanToSlice loads channel messages to slice until channel is closed
func ChanToSlice[T any](inCh chan T) []T {
s := make([]T, 0)
for v := range inCh {
s = append(s, v)
}
return s
}
// ChanToSliceN loads up to n elements from to slice to channel
func ChanToSliceN[T any](inCh chan T, n int) []T {
s := make([]T, 0)
idx := 0
for v := range inCh {
s = append(s, v)
idx++
if idx >= n {
return s
}
}
return s
}
// ChanToSliceNTimeout loads up to n elements from to slice to channel or up until timeout expires
func ChanToSliceNTimeout[T any](inCh chan T, n int, timeout time.Duration) []T {
s := make([]T, 0)
idx := 0
t := time.After(timeout)
for {
select {
case <-t:
return s
case v := <-inCh:
s = append(s, v)
idx++
if idx >= n {
return s
}
}
}
}
// SliceToChan feeds slice to channel
func SliceToChan[T any](in []T, out chan T, closeOutputChan ...bool) {
go func() {
for _, v := range in {
out <- v
}
if len(closeOutputChan) > 0 && closeOutputChan[0] {
close(out)
}
}()
return
}