-
Notifications
You must be signed in to change notification settings - Fork 1
/
stream_func.go
604 lines (522 loc) · 11.8 KB
/
stream_func.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
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
// Copyright © 2020 Yoshiki Shibata. All rights reserved.
package gostream
import (
"cmp"
"slices"
"sync"
"github.com/YoshikiShibata/gostream/function"
)
// Map returns a stream consisting of the results of applying the given
// function to the elements of the given stream.
func Map[T, R any](stream Stream[T], mapper function.Function[T, R]) Stream[R] {
gs := stream.(*genericStream[T])
gs.validateState()
nextReq := make(chan struct{})
nextData := make(chan orderedData[R])
closeCounter := gs.parallelCount
var lock sync.Mutex
closeChans := func() {
lock.Lock()
defer lock.Unlock()
if closeCounter > 1 {
closeCounter--
return
}
close(nextData)
close(gs.nextReq)
go func() {
for range nextReq {
}
}()
}
parallelCount := gs.parallelCount
for i := 0; i < parallelCount; i++ {
go func() {
for range nextReq {
gs.nextReq <- struct{}{}
od, ok := <-gs.nextData
if !ok {
closeChans()
return
}
r := mapper(od.data)
nextData <- orderedData[R]{
order: od.order,
data: r,
}
}
}()
}
return &genericStream[R]{
parallel: gs.parallel,
parallelCount: parallelCount,
nextReq: nextReq,
nextData: nextData,
}
}
// FlatMap returns a stream consisting of the results of replacing each
// element of stream with the contents of mapped stream produced by applying
// the provided mapping function to each element.
func FlatMap[T, R any](
stream Stream[T],
mapper function.Function[T, Stream[R]],
) Stream[R] {
gs := stream.(*genericStream[T])
gs.validateState()
nextReq := make(chan struct{})
nextData := make(chan orderedData[R])
var rgs *genericStream[R]
offset := uint64(0)
lastOrder := uint64(0)
go func() {
for range nextReq {
for {
if rgs == nil {
gs.nextReq <- struct{}{}
od, ok := <-gs.nextData
if !ok {
close(nextData)
close(gs.nextReq)
go func() {
for range nextReq {
}
}()
return
}
r := mapper(od.data)
rgs = r.(*genericStream[R])
}
rgs.nextReq <- struct{}{}
r, ok := <-rgs.nextData
if !ok {
close(rgs.nextReq)
rgs = nil
offset += lastOrder + 1
} else {
lastOrder = r.order
nextData <- orderedData[R]{
order: r.order + offset,
data: r.data,
}
break
}
}
}
}()
// Always return non-parallel stream
return &genericStream[R]{
parallelCount: 1,
nextReq: nextReq,
nextData: nextData,
}
}
// Returns a sequential ordered stream whose elements are the specified
// values.
func Of[T any](data ...T) Stream[T] {
nextReq := make(chan struct{})
nextData := make(chan orderedData[T])
prevDone := make(chan struct{})
go func() {
i := 0
for range nextReq {
if i == len(data) {
close(nextData)
close(prevDone)
go func() {
for range nextReq {
}
}()
return
}
if i < len(data) {
nextData <- orderedData[T]{
order: uint64(i),
data: data[i],
}
i++
}
}
close(nextData)
close(prevDone)
}()
return &genericStream[T]{
parallelCount: 1,
prevDone: prevDone,
nextReq: nextReq,
nextData: nextData,
}
}
// Distinct returns a stream consisting of the distinct elements
// (according to ==) of this stream.
func Distinct[T comparable](stream Stream[T]) Stream[T] {
s := stream.(*genericStream[T])
s.validateState()
gs := &genericStream[T]{
parallelCount: 1,
prevReq: s.nextReq,
prevData: s.nextData,
nextReq: make(chan struct{}),
nextData: make(chan orderedData[T]),
}
go func() {
seen := make(map[T]bool)
for range gs.nextReq {
od, ok := gs.getPrevData()
if !ok {
gs.close()
return
}
for seen[od.data] {
od, ok = gs.getPrevData()
if !ok {
gs.close()
return
}
}
gs.nextData <- od
seen[od.data] = true
}
gs.close()
}()
return gs
}
// Sorted returns a stream consisting of the elements of stream, sorted
// according to natural order.
func Sorted[T cmp.Ordered](stream Stream[T]) Stream[T] {
s := stream.(*genericStream[T])
s.validateState()
prevReq := s.nextReq
prevData := s.nextData
var dataSlice []T
for {
prevReq <- struct{}{}
od, ok := <-prevData
if !ok {
break
}
dataSlice = append(dataSlice, od.data)
}
close(prevReq)
slices.SortFunc(dataSlice, func(a, b T) int {
if a == b {
return 0
}
if a < b {
return -1
}
return 1
})
return Of(dataSlice...)
}
// Reduce performs a reduction on the elements of stream, using the provided
// identity, accumulation and combining functions.
func Reduce[U, T any](
stream Stream[T],
identity U,
accumulator function.BiFunction[U, T, U],
combiner function.BinaryOperator[U],
) U {
s := stream.(*genericStream[T])
s.validateState()
prevReq := s.nextReq
prevData := s.nextData
results := make(chan U)
parallelCount := s.parallelCount
for i := 0; i < parallelCount; i++ {
go func() {
result := identity
for {
prevReq <- struct{}{}
od, ok := <-prevData
if !ok {
break
}
result = accumulator(result, od.data)
}
results <- result
}()
}
result := identity
for i := 0; i < parallelCount; i++ {
result = combiner(result, <-results)
}
close(prevReq)
close(results)
return result
}
// Collect performs mutable reduction opertion on the elements of stream. A
// mutable result is one in which reduced value is a mutable result container
// such as a slice.
func Collect[R, T any](
stream Stream[T],
supplier function.Supplier[R],
accumulator function.BiConsumer[R, T],
combiner function.BiConsumer[R, R],
) R {
s := stream.(*genericStream[T])
s.validateState()
prevReq := s.nextReq
prevData := s.nextData
results := make(chan R)
parallelCount := s.parallelCount
for i := 0; i < parallelCount; i++ {
go func() {
result := supplier()
for {
prevReq <- struct{}{}
od, ok := <-prevData
if !ok {
break
}
accumulator(result, od.data)
}
results <- result
}()
}
result := supplier()
for i := 0; i < parallelCount; i++ {
combiner(result, <-results)
}
close(prevReq)
close(results)
return result
}
// CollectByCollector performs mutable reduction operation on the elements of
// stream using a Collector. A Collector encapsulates the functions used as
// arguments to Collect(Supplier, BiConsumer, BiConsumer), allowing for
// resuse of collection strategies and composition of collect operations such
// as multiple-level grouping or partitioning.
func CollectByCollector[T, R, A any](
stream Stream[T],
collector *Collector[T, A, R],
) R {
supplier := collector.Supplier()
accumulator := collector.Accumulator()
combiner := func(r, t A) {
_ = collector.Combiner()(r, t)
}
a := Collect(stream, supplier, accumulator, combiner)
return collector.Finisher()(a)
}
// Empty returns an empty Stream
func Empty[T any]() Stream[T] {
gs := &genericStream[T]{
parallelCount: 1,
nextReq: make(chan struct{}),
nextData: make(chan orderedData[T]),
}
go func() {
for range gs.nextReq {
// discard all requests
}
}()
close(gs.nextData)
return gs
}
// Iterate returns an infinite sequential ordered Stream produces by iterative
// appliation of a function f to an initial element seed, producing a Stream
// consisiting of seed, f(seed), f(f(seed)), etc.
func Iterate[T any](seed T, f function.UnaryOperator[T]) Stream[T] {
gs := &genericStream[T]{
parallelCount: 1,
nextReq: make(chan struct{}, goMaxProcs),
nextData: make(chan orderedData[T], goMaxProcs),
}
go func() {
useSeed := true
nextValue := seed
order := uint64(0)
for range gs.nextReq {
if useSeed {
gs.nextData <- orderedData[T]{
order: order,
data: seed,
}
useSeed = false
} else {
nextValue = f(nextValue)
gs.nextData <- orderedData[T]{
order: order,
data: nextValue,
}
}
order++
}
close(gs.nextData)
}()
return gs
}
// IterateN returns a sequential ordered Stream produced by iterative
// application of the given next function to an initial element,
// conditioned on satisfying the given code hasNext predicate.
// stream terminates as soon as the code hasNext predicate returns false.
func IterateN[T any](
seed T,
hasNext function.Predicate[T],
next function.UnaryOperator[T]) Stream[T] {
gs := &genericStream[T]{
parallelCount: 1,
nextReq: make(chan struct{}),
nextData: make(chan orderedData[T]),
}
go func() {
nextValue := seed
applyNext := false
order := uint64(0)
for range gs.nextReq {
if applyNext {
nextValue = next(nextValue)
}
if !hasNext(nextValue) {
break
}
gs.nextData <- orderedData[T]{
order: order,
data: nextValue,
}
order++
applyNext = true
}
close(gs.nextData)
}()
return gs
}
// Generate returns an infinite sequential unordered stream where each element
// is generated by the provided Supplier. This is suitable for generating
// constant streams, streams of random elements, etc.
func Generate[T any](s function.Supplier[T]) Stream[T] {
gs := &genericStream[T]{
parallelCount: 1,
nextReq: make(chan struct{}),
nextData: make(chan orderedData[T]),
}
go func() {
order := uint64(0)
for range gs.nextReq {
gs.nextData <- orderedData[T]{
order: order,
data: s(),
}
order++
}
close(gs.nextData)
}()
return gs
}
// Concat a lazily concatenated stream whose elements are all the elements of
// the first stream followed by all the elements of the second stream.
func Concat[T any](a, b Stream[T]) Stream[T] {
ags := a.(*genericStream[T])
bgs := b.(*genericStream[T])
ags.validateState()
bgs.validateState()
// The concatenated stream is always not parallel.
gs := &genericStream[T]{
parallelCount: 1,
nextReq: make(chan struct{}),
nextData: make(chan orderedData[T]),
}
go func() {
gs.prevReq = ags.nextReq
gs.prevData = ags.nextData
switchedToB := false
offset := uint64(0)
lastOrder := uint64(0)
for range gs.nextReq {
data, ok := gs.getPrevData()
if !ok {
if switchedToB {
gs.close()
return
}
gs.prevReq = bgs.nextReq
gs.prevData = bgs.nextData
switchedToB = true
offset = lastOrder + 1
data, ok = gs.getPrevData()
if !ok {
gs.close()
return
}
}
lastOrder = data.order
gs.nextData <- orderedData[T]{
order: data.order + offset,
data: data.data,
}
}
gs.close()
}()
return gs
}
// Returns the sum of elements in this stream.
func Sum[T Number](stream Stream[T]) T {
gs := stream.(*genericStream[T])
gs.validateState()
if !gs.parallel {
var sum T
gs.terminalOp(func(t T) {
sum += t
})
return sum
}
sums := make(chan T)
parallelCount := gs.parallelCount
for i := 0; i < parallelCount; i++ {
go func() {
var sum T
gs.terminalOp(func(t T) {
sum += t
})
sums <- sum
}()
}
var sum T
for i := 0; i < parallelCount; i++ {
sum += <-sums
}
close(sums)
return sum
}
// Range returns a sequential ordered Stream from startInclusive to
// endExclusive (exclusive) by an incremental step of 1.
func Range[T Number](
startInclusive T,
endExclusive T,
) Stream[T] {
return Iterate(
startInclusive,
func(t T) T {
return t + 1
},
).Limit(int(endExclusive - startInclusive))
}
// RangeClosed returns a sequential ordered Stream from staticInclusive to
// endInclusive (inclusive) by an incremental step of 1.
func RangeClosed[T Number](
startInclusive T,
endInclusive T,
) Stream[T] {
return Iterate(
startInclusive,
func(t T) T {
return t + 1
},
).Limit(int(endInclusive - startInclusive + 1))
}
// Max returns the maximum element of a stream.
func Max[T Number](
stream Stream[T],
) *Optional[T] {
return stream.Max(func(x, y T) bool {
return x < y
})
}
// Min returns the minimum element of a stream.
func Min[T Number](
stream Stream[T],
) *Optional[T] {
return stream.Min(func(x, y T) bool {
return x < y
})
}