-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathchannel_ctx.go
More file actions
619 lines (586 loc) · 12.5 KB
/
channel_ctx.go
File metadata and controls
619 lines (586 loc) · 12.5 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package channels
import (
"context"
"reflect"
"sync"
"github.com/life4/genesis/constraints"
)
// All returns true if f returns true for all elements in channel.
func AllC[T any](ctx context.Context, c <-chan T, f func(el T) bool) bool {
for {
select {
case el, ok := <-c:
if !ok {
return true
}
if !f(el) {
return false
}
case <-ctx.Done():
return true
}
}
}
// Any returns true if f returns true for any element in channel.
func AnyC[T any](ctx context.Context, c <-chan T, f func(el T) bool) bool {
for {
select {
case el, ok := <-c:
if !ok {
return false
}
if f(el) {
return true
}
case <-ctx.Done():
return false
}
}
}
// ChunkEveryC returns channel with slices containing count elements each.
func ChunkEveryC[T any](ctx context.Context, c <-chan T, count int) chan []T {
chunks := make(chan []T, 1)
go func() {
defer close(chunks)
chunk := make([]T, 0, count)
i := 0
for el := range WithContext(c, ctx) {
chunk = append(chunk, el)
i++
if i%count == 0 {
i = 0
select {
case chunks <- chunk:
case <-ctx.Done():
return
}
chunk = make([]T, 0, count)
}
}
if len(chunk) > 0 {
select {
case chunks <- chunk:
case <-ctx.Done():
return
}
}
}()
return chunks
}
// Count return count of el occurrences in channel.
func CountC[T comparable](ctx context.Context, c <-chan T, el T) int {
count := 0
for {
select {
case val, ok := <-c:
if !ok {
return count
}
if val == el {
count++
}
case <-ctx.Done():
return count
}
}
}
// Drop drops first n elements from channel c and returns a new channel with the rest.
func DropC[T any](ctx context.Context, c <-chan T, n int) chan T {
result := make(chan T)
go func() {
defer close(result)
i := 0
for {
select {
case el, ok := <-c:
if !ok {
return
}
if i >= n {
select {
case result <- el:
case <-ctx.Done():
return
}
}
i++
case <-ctx.Done():
return
}
}
}()
return result
}
// Each calls f for every element in the channel.
func EachC[T any](ctx context.Context, c <-chan T, f func(el T)) {
for {
select {
case el, ok := <-c:
if !ok {
return
}
f(el)
case <-ctx.Done():
return
}
}
}
// EchoC moves messages from one channel to the other.
//
// If you want to move messages from multiple channels into one, use [MergeC] instead.
//
// If you want to move messages from one channel into multiple, use [TeeC] instead.
func EchoC[T any](ctx context.Context, from <-chan T, to chan<- T) {
for {
select {
case el, ok := <-from:
if !ok {
return
}
select {
case to <- el:
case <-ctx.Done():
return
}
case <-ctx.Done():
return
}
}
}
// Filter returns a new channel with elements from input channel for which f returns true.
func FilterC[T any](ctx context.Context, c <-chan T, f func(el T) bool) chan T {
result := make(chan T)
go func() {
defer close(result)
for {
select {
case el, ok := <-c:
if !ok {
return
}
if f(el) {
select {
case result <- el:
case <-ctx.Done():
return
}
}
case <-ctx.Done():
return
}
}
}()
return result
}
// FirstC selects the first available element from the given channels.
//
// The function returns in one of the following cases:
//
// 1. One of the given channels is closed. In this case,
// [ErrClosed] is returned.
// 2. The ctx context is canceled. In this case,
// the cancelation reason is returned as an error.
// 3. One of the given channels returns a value. In this case,
// the error is nil.
//
// If all channels are non-closed and empty and ctx is not canceled,
// the function will block and wait for one of the above to occur.
//
// If a message available in multiple channels, only one is chosen
// via a uniform pseudo-random selection to avoid [starvation].
//
// # 😱 Errors
//
// - [ErrEmpty]: no channels are passed into the function.
// - [ErrClosed]: a channel was closed.
// - Another: cancelation cause returned by ctx.Err().
//
// [starvation]: https://en.wikipedia.org/wiki/Starvation_(computer_science)
func FirstC[T any](ctx context.Context, cs ...<-chan T) (T, error) {
// try to use a regular select if a small number of channels is passed
switch len(cs) {
case 0:
return *new(T), ErrEmpty
case 1:
select {
case v, ok := <-cs[0]:
if !ok {
return *new(T), ErrClosed
}
return v, nil
case <-ctx.Done():
return *new(T), ctx.Err()
}
}
cases := make([]reflect.SelectCase, 0, len(cs)+1)
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ctx.Done()),
})
for _, c := range cs {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(c),
})
}
chosen, rval, ok := reflect.Select(cases)
if chosen == 0 {
var v T
return v, ctx.Err()
}
val := rval.Interface().(T)
if !ok {
return val, ErrClosed
}
return val, nil
}
// Given a channel of channels of values, return a channel of values.
//
// This pattern is described in the "Concurrency in Go" book
// as "the Bridge channel" pattern. It might be useful when you design
// your system as a pipeline consisting of goroutines connected through
// channels and you have steps producing new steps.
func FlattenC[T any](ctx context.Context, c <-chan <-chan T) chan T {
result := make(chan T)
go func() {
defer close(result)
for {
select {
case stream, ok := <-c:
if !ok {
return
}
EchoC(ctx, stream, result)
case <-ctx.Done():
return
}
}
}()
return result
}
// Map applies f to all elements from channel and returns channel with results.
func MapC[T any, G any](ctx context.Context, c <-chan T, f func(el T) G) chan G {
result := make(chan G, 1)
go func() {
defer close(result)
for {
select {
case el, ok := <-c:
if !ok {
return
}
select {
case result <- f(el):
case <-ctx.Done():
return
}
case <-ctx.Done():
return
}
}
}()
return result
}
// Max returns the maximal element from channel.
func MaxC[T constraints.Ordered](ctx context.Context, c <-chan T) (T, error) {
select {
case max, ok := <-c:
if !ok {
return max, ErrEmpty
}
for {
select {
case el, ok := <-c:
if !ok {
return max, nil
}
if el > max {
max = el
}
case <-ctx.Done():
return max, ctx.Err()
}
}
case <-ctx.Done():
var max T
return max, ctx.Err()
}
}
// MergeC merges multiple channels into one.
//
// The order in which elements are merged from different channels
// is not guaranteed.
func MergeC[T any](ctx context.Context, cs ...<-chan T) chan T {
res := make(chan T)
// make sure the result channel is closed
// when all input channels are closed
wg := sync.WaitGroup{}
wg.Add(len(cs))
go func() {
wg.Wait()
close(res)
}()
echo := func(c <-chan T) {
defer wg.Done()
for {
select {
case v, ok := <-c:
if !ok {
return
}
select {
case res <- v:
case <-ctx.Done():
return
}
case <-ctx.Done():
return
}
}
}
for _, c := range cs {
go echo(c)
}
return res
}
// Min returns the minimal element from channel.
func MinC[T constraints.Ordered](ctx context.Context, c <-chan T) (T, error) {
select {
case min, ok := <-c:
if !ok {
return min, ErrEmpty
}
for {
select {
case el, ok := <-c:
if !ok {
return min, nil
}
if el < min {
min = el
}
case <-ctx.Done():
return min, ctx.Err()
}
}
case <-ctx.Done():
var min T
return min, ctx.Err()
}
}
// Pop reads a value from the channel (with context).
//
// The function is blocking. It will wait and return
// in one of the following conditions:
//
// 1. ⏹️ The context is canceled.
// 2. ⏹️ The channel is closed.
// 3. There is a value pushed into the channel.
//
// In the first two cases, the second return value (called "more" or "ok") is "false".
// Otherwise, if a value is succesfully pulled from the channel, it is "true".
//
// Reads from nil channels block forever. So, if a nil channel is passed,
// the function will exit only when the context is canceled.
func Pop[T any](ctx context.Context, c <-chan T) (T, bool) {
select {
case v, more := <-c:
return v, more
case <-ctx.Done():
return *new(T), false
}
}
// Push writes the value into the channel (with context).
//
// ⚠️ Experimental! Behavior of this function might change in the future
// or the function can be removed altogether.
// It's not clear yet what's the best approach for when the target channel is closed.
// By default, Go panics in this case, which might be not good in some situations.
// Also, using this function might cause situations when the canceled context
// will be ignored by the target function instead of exiting.
func Push[T any](ctx context.Context, c chan<- T, v T) {
select {
case c <- v:
case <-ctx.Done():
}
}
// Reduce applies f to acc and every element from channel and returns acc.
func ReduceC[T any, G any](ctx context.Context, c <-chan T, acc G, f func(el T, acc G) G) G {
for {
select {
case el, ok := <-c:
if !ok {
return acc
}
acc = f(el, acc)
case <-ctx.Done():
return acc
}
}
}
// Scan is like Reduce, but returns slice of f results.
func ScanC[T any, G any](ctx context.Context, c <-chan T, acc G, f func(el T, acc G) G) chan G {
result := make(chan G, 1)
go func() {
defer close(result)
for {
select {
case el, ok := <-c:
if !ok {
return
}
acc = f(el, acc)
select {
case result <- acc:
case <-ctx.Done():
return
}
case <-ctx.Done():
return
}
}
}()
return result
}
// Sum returns sum of all elements from channel.
func SumC[T constraints.Ordered](ctx context.Context, c <-chan T) T {
var sum T
for {
select {
case el, ok := <-c:
if !ok {
return sum
}
sum += el
case <-ctx.Done():
return sum
}
}
}
// Take takes first count elements from the channel.
func TakeC[T any](ctx context.Context, c <-chan T, count int) chan T {
result := make(chan T)
go func() {
defer close(result)
if count <= 0 {
return
}
i := 0
for {
select {
case el, ok := <-c:
if !ok {
return
}
select {
case result <- el:
case <-ctx.Done():
return
}
i++
if i == count {
return
}
case <-ctx.Done():
return
}
}
}()
return result
}
// Tee returns "count" number of channels with elements from the input channel.
func TeeC[T any](ctx context.Context, c <-chan T, count int) []chan T {
channels := make([]chan T, 0, count)
for i := 0; i < count; i++ {
channels = append(channels, make(chan T))
}
go func() {
defer func() {
for _, ch := range channels {
close(ch)
}
}()
for {
select {
case el, ok := <-c:
if !ok {
return
}
wg := sync.WaitGroup{}
putInto := func(ch chan T) {
defer wg.Done()
select {
case ch <- el:
case <-ctx.Done():
}
}
wg.Add(count)
for _, ch := range channels {
go putInto(ch)
}
wg.Wait()
case <-ctx.Done():
return
}
}
}()
return channels
}
// ToSlice returns slice with all elements from channel.
func ToSliceC[T any](ctx context.Context, c <-chan T) []T {
result := make([]T, 0)
for {
select {
case el, ok := <-c:
if !ok {
return result
}
result = append(result, el)
case <-ctx.Done():
return result
}
}
}
// WithBuffer creates an echo channel of the given one with the given buffer size.
//
// This function effectively makes writes into the given channel non-blocking
// until the buffer size of pending messages is reached, assuming that all reads
// will be done only from the channel that the function returns.
func WithBufferC[T any](ctx context.Context, c <-chan T, bufSize int) chan T {
result := make(chan T, bufSize)
go func() {
defer close(result)
EchoC(ctx, c, result)
}()
return result
}
// WithContext creates an echo channel of the given one that can be canceled with ctx.
//
// This can be useful in 2 scenarios:
//
// 1. To be able to cancel any function in this package
// without closing the original channel.
// 2. For simpler iteration through channels with support for cancellation.
// This pattern is descirbed in the "Concurrency in Go" book
// in "The or-done-channel" chapter (page 119).
func WithContext[T any](c <-chan T, ctx context.Context) chan T {
result := make(chan T)
go func() {
defer close(result)
for {
select {
case <-ctx.Done():
return
case val, more := <-c:
if !more {
return
}
select {
case result <- val:
case <-ctx.Done():
}
}
}
}()
return result
}