-
Notifications
You must be signed in to change notification settings - Fork 597
/
Stream.scala
4884 lines (4453 loc) · 189 KB
/
Stream.scala
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013 Functional Streams for Scala
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fs2
import scala.annotation.tailrec
import scala.concurrent.TimeoutException
import scala.concurrent.duration._
import java.io.PrintStream
import cats.{Eval => _, _}
import cats.data.Ior
import cats.effect.SyncIO
import cats.effect.kernel._
import cats.effect.std.{CountDownLatch, Queue, Semaphore}
import cats.effect.kernel.implicits._
import cats.implicits.{catsSyntaxEither => _, _}
import fs2.compat._
import fs2.concurrent._
import fs2.internal._
import scala.collection.mutable.ArrayBuffer
/** A stream producing output of type `O` and which may evaluate `F` effects.
*
* - '''Purely functional''' a value of type `Stream[F, O]` _describes_ an effectful computation.
* A function that returns a `Stream[F, O]` builds a _description_ of an effectful computation,
* but does not perform them. The methods of the `Stream` class derive new descriptions from others.
* This is similar to how effect types like `cats.effect.IO` and `monix.Task` build descriptions of
* computations.
*
* - '''Pull''': to evaluate a stream, a consumer pulls its values from it, by repeatedly performing one pull step at a time.
* Each step is a `F`-effectful computation that may yield some `O` values (or none), and a stream from which to continue pulling.
* The consumer controls the evaluation of the stream, which effectful operations are performed, and when.
*
* - '''Non-Strict''': stream evaluation only pulls from the stream a prefix large enough to compute its results.
* Thus, although a stream may yield an unbounded number of values or, after successfully yielding several values,
* either raise an error or hang up and never yield any value, the consumer need not reach those points of failure.
* For the same reason, in general, no effect in `F` is evaluated unless and until the consumer needs it.
*
* - '''Abstract''': a stream needs not be a plain finite list of fixed effectful computations in F.
* It can also represent an input or output connection through which data incrementally arrives.
* It can represent an effectful computation, such as reading the system's time, that can be re-evaluated
* as often as the consumer of the stream requires.
*
* === Special properties for streams ===
*
* There are some special properties or cases of streams:
* - A stream is '''finite''' if we can reach the end after a limited number of pull steps,
* which may yield a finite number of values. It is '''empty''' if it terminates and yields no values.
* - A '''singleton''' stream is a stream that ends after yielding one single value.
* - A '''pure''' stream is one in which the `F` is [[Pure]], which indicates that it evaluates no effects.
* - A '''never''' stream is a stream that never terminates and never yields any value.
*
* == Pure Streams and operations ==
*
* We can sometimes think of streams, naively, as lists of `O` elements with `F`-effects.
* This is particularly true for '''pure''' streams, which are instances of `Stream` which use the [[Pure]] effect type.
* We can convert every ''pure and finite'' stream into a `List[O]` using the `.toList` method.
* Also, we can convert pure ''infinite'' streams into instances of the `Stream[O]` class from the Scala standard library.
*
* A method of the `Stream` class is '''pure''' if it can be applied to pure streams. Such methods are identified
* in that their signature includes no type-class constraint (or implicit parameter) on the `F` method.
* Pure methods in `Stream[F, O]` can be projected ''naturally'' to methods in the `List` class, which means
* that applying the stream's method and converting the result to a list gets the same result as
* first converting the stream to a list, and then applying list methods.
*
* Some methods that project directly to list are `map`, `filter`, `takeWhile`, etc.
* There are other methods, like `exists` or `find`, that in the `List` class they return a value or an `Option`,
* but their stream counterparts return an (either empty or singleton) stream.
* Other methods, like `zipWithPrevious`, have a more complicated but still pure translation to list methods.
*
* == Type-Class instances and laws of the Stream Operations ==
*
* Laws (using infix syntax):
*
* `append` forms a monoid in conjunction with `empty`:
* - `empty append s == s` and `s append empty == s`.
* - `(s1 append s2) append s3 == s1 append (s2 append s3)`
*
* And `cons` is consistent with using `++` to prepend a single chunk:
* - `s.cons(c) == Stream.chunk(c) ++ s`
*
* `Stream.raiseError` propagates until being caught by `handleErrorWith`:
* - `Stream.raiseError(e) handleErrorWith h == h(e)`
* - `Stream.raiseError(e) ++ s == Stream.raiseError(e)`
* - `Stream.raiseError(e) flatMap f == Stream.raiseError(e)`
*
* `Stream` forms a monad with `emit` and `flatMap`:
* - `Stream.emit >=> f == f` (left identity)
* - `f >=> Stream.emit === f` (right identity - note weaker equality notion here)
* - `(f >=> g) >=> h == f >=> (g >=> h)` (associativity)
* where `Stream.emit(a)` is defined as `chunk(Chunk.singleton(a)) and
* `f >=> g` is defined as `a => a flatMap f flatMap g`
*
* The monad is the list-style sequencing monad:
* - `(a ++ b) flatMap f == (a flatMap f) ++ (b flatMap f)`
* - `Stream.empty flatMap f == Stream.empty`
*
* == Technical notes==
*
* ''Note:'' since the chunk structure of the stream is observable, and
* `s flatMap Stream.emit` produces a stream of singleton chunks,
* the right identity law uses a weaker notion of equality, `===` which
* normalizes both sides with respect to chunk structure:
*
* `(s1 === s2) = normalize(s1) == normalize(s2)`
* where `==` is full equality
* (`a == b` iff `f(a)` is identical to `f(b)` for all `f`)
*
* `normalize(s)` can be defined as `s.flatMap(Stream.emit)`, which just
* produces a singly-chunked stream from any input stream `s`.
*
* For instance, for a stream `s` and a function `f: A => B`,
* - the result of `s.map(f)` is a Stream with the same _chunking_ as the `s`; wheras...
* - the result of `s.flatMap(x => S.emit(f(x)))` is a Stream structured as a sequence of singleton chunks.
* The latter is using the definition of `map` that is derived from the `Monad` instance.
*
* This is not unlike equality for maps or sets, which is defined by which elements they contain,
* not by how these are spread between a tree's branches or a hashtable buckets.
* However, a `Stream` structure can be _observed_ through the `chunks` method,
* so two streams "_equal_" under that notion may give different results through this method.
*
* ''Note:'' For efficiency `[[Stream.map]]` function operates on an entire
* chunk at a time and preserves chunk structure, which differs from
* the `map` derived from the monad (`s map f == s flatMap (f andThen Stream.emit)`)
* which would produce singleton chunk. In particular, if `f` throws errors, the
* chunked version will fail on the first ''chunk'' with an error, while
* the unchunked version will fail on the first ''element'' with an error.
* Exceptions in pure code like this are strongly discouraged.
*
* @hideImplicitConversion PureOps
* @hideImplicitConversion IdOps
*/
final class Stream[+F[_], +O] private[fs2] (private[fs2] val underlying: Pull[F, O, Unit]) {
/** Appends `s2` to the end of this stream.
*
* @example {{{
* scala> (Stream(1,2,3) ++ Stream(4,5,6)).toList
* res0: List[Int] = List(1, 2, 3, 4, 5, 6)
* }}}
*
* If `this` stream is infinite, then the result is equivalent to `this`.
*/
def ++[F2[x] >: F[x], O2 >: O](s2: => Stream[F2, O2]): Stream[F2, O2] =
new Stream(underlying >> s2.underlying)
/** Appends `s2` to the end of this stream. Alias for `s1 ++ s2`. */
def append[F2[x] >: F[x], O2 >: O](s2: => Stream[F2, O2]): Stream[F2, O2] =
this ++ s2
/** Equivalent to `val o2Memoized = o2; _.map(_ => o2Memoized)`.
*
* @example {{{
* scala> Stream(1,2,3).as(0).toList
* res0: List[Int] = List(0, 0, 0)
* }}}
*/
def as[O2](o2: O2): Stream[F, O2] = map(_ => o2)
/** Returns a stream of `O` values wrapped in `Right` until the first error, which is emitted wrapped in `Left`.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> (Stream(1,2,3) ++ Stream.raiseError[SyncIO](new RuntimeException) ++ Stream(4,5,6)).attempt.compile.toList.unsafeRunSync()
* res0: List[Either[Throwable,Int]] = List(Right(1), Right(2), Right(3), Left(java.lang.RuntimeException))
* }}}
*
* [[rethrow]] is the inverse of `attempt`, with the caveat that anything after the first failure is discarded.
*/
def attempt: Stream[F, Either[Throwable, O]] =
map(Right(_): Either[Throwable, O]).handleErrorWith(e => Stream.emit(Left(e)))
/** Retries on failure, returning a stream of attempts that can
* be manipulated with standard stream operations such as `take`,
* `collectFirst` and `interruptWhen`.
*
* Note: The resulting stream does *not* automatically halt at the
* first successful attempt. Also see `retry`.
*/
def attempts[F2[x] >: F[x]: Temporal](
delays: Stream[F2, FiniteDuration]
): Stream[F2, Either[Throwable, O]] =
attempt ++ delays.flatMap(delay => Stream.sleep_(delay) ++ attempt)
/** Broadcasts every value of the stream through the pipes provided
* as arguments.
*
* Each pipe can have a different implementation if required, and
* they are all guaranteed to see every `O` pulled from the source
* stream.
*
* The pipes are all run concurrently with each other, but note
* that elements are pulled from the source as chunks, and the next
* chunk is pulled only when all pipes are done with processing the
* current chunk, which prevents faster pipes from getting too far ahead.
*
* In other words, this behaviour slows down processing of incoming
* chunks by faster pipes until the slower ones have caught up. If
* this is not desired, consider using the `prefetch` and
* `prefetchN` combinators on the slow pipes.
*/
def broadcastThrough[F2[x] >: F[x]: Concurrent, O2](
pipes: Pipe[F2, O, O2]*
): Stream[F2, O2] =
Stream
.eval {
(
CountDownLatch[F2](pipes.length),
fs2.concurrent.Topic[F2, Option[Chunk[O]]]
).tupled
}
.flatMap { case (latch, topic) =>
def produce = chunks.noneTerminate.through(topic.publish)
def consume(pipe: Pipe[F2, O, O2]): Pipe[F2, Option[Chunk[O]], O2] =
_.unNoneTerminate.flatMap(Stream.chunk).through(pipe)
Stream(pipes: _*)
.map { pipe =>
Stream
.resource(topic.subscribeAwait(1))
.flatMap { sub =>
// crucial that awaiting on the latch is not passed to
// the pipe, so that the pipe cannot interrupt it and alter
// the latch count
Stream.exec(latch.release >> latch.await) ++ sub.through(consume(pipe))
}
}
.parJoinUnbounded
.concurrently(Stream.eval(latch.await) ++ produce)
}
/** Behaves like the identity function, but requests `n` elements at a time from the input.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> val buf = new scala.collection.mutable.ListBuffer[String]()
* scala> Stream.range(0, 100).covary[SyncIO].
* | evalMap(i => SyncIO { buf += s">$i"; i }).
* | buffer(4).
* | evalMap(i => SyncIO { buf += s"<$i"; i }).
* | take(10).
* | compile.toVector.unsafeRunSync()
* res0: Vector[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
* scala> buf.toList
* res1: List[String] = List(>0, >1, >2, >3, <0, <1, <2, <3, >4, >5, >6, >7, <4, <5, <6, <7, >8, >9, >10, >11, <8, <9)
* }}}
*/
def buffer(n: Int): Stream[F, O] =
if (n <= 0) this
else
this.repeatPull {
_.unconsN(n, allowFewer = true).flatMap {
case Some((hd, tl)) => Pull.output(hd).as(Some(tl))
case None => Pull.pure(None)
}
}
/** Behaves like the identity stream, but emits no output until the source is exhausted.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> val buf = new scala.collection.mutable.ListBuffer[String]()
* scala> Stream.range(0, 10).covary[SyncIO].
* | evalMap(i => SyncIO { buf += s">$i"; i }).
* | bufferAll.
* | evalMap(i => SyncIO { buf += s"<$i"; i }).
* | take(4).
* | compile.toVector.unsafeRunSync()
* res0: Vector[Int] = Vector(0, 1, 2, 3)
* scala> buf.toList
* res1: List[String] = List(>0, >1, >2, >3, >4, >5, >6, >7, >8, >9, <0, <1, <2, <3)
* }}}
*/
def bufferAll: Stream[F, O] = bufferBy(_ => true)
/** Behaves like the identity stream, but requests elements from its
* input in blocks that end whenever the predicate switches from true to false.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> val buf = new scala.collection.mutable.ListBuffer[String]()
* scala> Stream.range(0, 10).covary[SyncIO].
* | evalMap(i => SyncIO { buf += s">$i"; i }).
* | bufferBy(_ % 2 == 0).
* | evalMap(i => SyncIO { buf += s"<$i"; i }).
* | compile.toVector.unsafeRunSync()
* res0: Vector[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
* scala> buf.toList
* res1: List[String] = List(>0, >1, <0, <1, >2, >3, <2, <3, >4, >5, <4, <5, >6, >7, <6, <7, >8, >9, <8, <9)
* }}}
*/
def bufferBy(f: O => Boolean): Stream[F, O] = {
def dumpBuffer(bb: List[Chunk[O]]): Pull[F, O, Unit] =
bb.reverse.foldLeft(Pull.done: Pull[F, O, Unit])((acc, c) => acc >> Pull.output(c))
def go(buffer: List[Chunk[O]], last: Boolean, s: Stream[F, O]): Pull[F, O, Unit] =
s.pull.uncons.flatMap {
case Some((hd, tl)) =>
val (out, buf, newLast) =
hd.foldLeft((Nil: List[Chunk[O]], Vector.empty[O], last)) {
case ((out, buf, last), i) =>
val cur = f(i)
if (!cur && last)
(Chunk.vector(buf :+ i) :: out, Vector.empty, cur)
else (out, buf :+ i, cur)
}
if (out.isEmpty)
go(Chunk.vector(buf) :: buffer, newLast, tl)
else
dumpBuffer(buffer) >> dumpBuffer(out) >> go(List(Chunk.vector(buf)), newLast, tl)
case None => dumpBuffer(buffer)
}
go(Nil, false, this).stream
}
/** Emits only elements that are distinct from their immediate predecessors,
* using natural equality for comparison.
*
* @example {{{
* scala> Stream(1,1,2,2,2,3,3).changes.toList
* res0: List[Int] = List(1, 2, 3)
* }}}
*/
def changes[O2 >: O](implicit eq: Eq[O2]): Stream[F, O2] =
filterWithPrevious(eq.neqv)
/** Emits only elements that are distinct from their immediate predecessors
* according to `f`, using natural equality for comparison.
*
* Note that `f` is called for each element in the stream multiple times
* and hence should be fast (e.g., an accessor). It is not intended to be
* used for computationally intensive conversions. For such conversions,
* consider something like: `src.map(o => (o, f(o))).changesBy(_._2).map(_._1)`
*
* @example {{{
* scala> Stream(1,1,2,4,6,9).changesBy(_ % 2).toList
* res0: List[Int] = List(1, 2, 9)
* }}}
*/
def changesBy[O2](f: O => O2)(implicit eq: Eq[O2]): Stream[F, O] =
filterWithPrevious((o1, o2) => eq.neqv(f(o1), f(o2)))
/** Collects all output chunks in to a single chunk and emits it at the end of the
* source stream. Note: if more than 2^32-1 elements are collected, this operation
* will fail.
*
* @example {{{
* scala> (Stream(1) ++ Stream(2, 3) ++ Stream(4, 5, 6)).chunkAll.toList
* res0: List[Chunk[Int]] = List(Chunk(1, 2, 3, 4, 5, 6))
* }}}
*/
def chunkAll: Stream[F, Chunk[O]] = {
def loop(s: Stream[F, O], acc: Chunk[O]): Pull[F, Chunk[O], Unit] =
s.pull.uncons.flatMap {
case Some((hd, tl)) => loop(tl, acc ++ hd)
case None => Pull.output1(acc)
}
loop(this, Chunk.empty).stream
}
/** Outputs all chunks from the source stream.
*
* @example {{{
* scala> (Stream(1) ++ Stream(2, 3) ++ Stream(4, 5, 6)).chunks.toList
* res0: List[Chunk[Int]] = List(Chunk(1), Chunk(2, 3), Chunk(4, 5, 6))
* }}}
*/
def chunks: Stream[F, Chunk[O]] =
this.repeatPull(_.uncons.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) => Pull.output1(hd).as(Some(tl))
})
/** Outputs chunk with a limited maximum size, splitting as necessary.
*
* @example {{{
* scala> (Stream(1) ++ Stream(2, 3) ++ Stream(4, 5, 6)).chunkLimit(2).toList
* res0: List[Chunk[Int]] = List(Chunk(1), Chunk(2, 3), Chunk(4, 5), Chunk(6))
* }}}
*/
def chunkLimit(n: Int): Stream[F, Chunk[O]] =
this.repeatPull {
_.unconsLimit(n).flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) => Pull.output1(hd).as(Some(tl))
}
}
/** Outputs chunks of size larger than N
*
* Chunks from the source stream are split as necessary.
*
* If `allowFewerTotal` is true,
* if the stream is smaller than N, should the elements be included
*
* @example {{{
* scala> (Stream(1,2) ++ Stream(3,4) ++ Stream(5,6,7)).chunkMin(3).toList
* res0: List[Chunk[Int]] = List(Chunk(1, 2, 3, 4), Chunk(5, 6, 7))
* }}}
*/
def chunkMin(n: Int, allowFewerTotal: Boolean = true): Stream[F, Chunk[O]] = {
// Untyped Guarantee: accFull.size >= n | accFull.size == 0
def go[A](nextChunk: Chunk[A], s: Stream[F, A]): Pull[F, Chunk[A], Unit] =
s.pull.uncons.flatMap {
case None =>
if (allowFewerTotal && nextChunk.size > 0)
Pull.output1(nextChunk)
else
Pull.done
case Some((hd, tl)) =>
val next = nextChunk ++ hd
if (next.size >= n)
Pull.output1(next) >> go(Chunk.empty, tl)
else
go(next, tl)
}
this.pull.uncons.flatMap {
case None => Pull.done
case Some((hd, tl)) =>
if (hd.size >= n)
Pull.output1(hd) >> go(Chunk.empty, tl)
else go(hd, tl)
}.stream
}
/** Outputs chunks of size `n`.
*
* Chunks from the source stream are split as necessary.
* If `allowFewer` is true, the last chunk that is emitted may have less than `n` elements.
*
* @example {{{
* scala> Stream(1,2,3).repeat.chunkN(2).take(5).toList
* res0: List[Chunk[Int]] = List(Chunk(1, 2), Chunk(3, 1), Chunk(2, 3), Chunk(1, 2), Chunk(3, 1))
* }}}
*/
def chunkN(n: Int, allowFewer: Boolean = true): Stream[F, Chunk[O]] =
this.repeatPull {
_.unconsN(n, allowFewer).flatMap {
case Some((hd, tl)) => Pull.output1(hd).as(Some(tl))
case None => Pull.pure(None)
}
}
/** Filters and maps simultaneously. Calls `collect` on each chunk in the stream.
*
* @example {{{
* scala> Stream(Some(1), Some(2), None, Some(3), None, Some(4)).collect { case Some(i) => i }.toList
* res0: List[Int] = List(1, 2, 3, 4)
* }}}
*/
def collect[O2](pf: PartialFunction[O, O2]): Stream[F, O2] =
mapChunks(_.collect(pf))
/** Emits the first element of the stream for which the partial function is defined.
*
* @example {{{
* scala> Stream(None, Some(1), Some(2), None, Some(3)).collectFirst { case Some(i) => i }.toList
* res0: List[Int] = List(1)
* }}}
*/
def collectFirst[O2](pf: PartialFunction[O, O2]): Stream[F, O2] =
this.pull
.find(pf.isDefinedAt)
.flatMap {
case None => Pull.done
case Some((hd, _)) => Pull.output1(pf(hd))
}
.stream
/** Like [[collect]] but terminates as soon as the partial function is undefined.
*
* @example {{{
* scala> Stream(Some(1), Some(2), Some(3), None, Some(4)).collectWhile { case Some(i) => i }.toList
* res0: List[Int] = List(1, 2, 3)
* }}}
*/
def collectWhile[O2](pf: PartialFunction[O, O2]): Stream[F, O2] =
takeWhile(pf.isDefinedAt).map(pf)
/** Gets a projection of this stream that allows converting it to an `F[..]` in a number of ways.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> val prg: SyncIO[Vector[Int]] = Stream.eval(SyncIO(1)).append(Stream(2,3,4)).compile.toVector
* scala> prg.unsafeRunSync()
* res2: Vector[Int] = Vector(1, 2, 3, 4)
* }}}
*/
def compile[F2[x] >: F[x], G[_], O2 >: O](implicit
compiler: Compiler[F2, G]
): Stream.CompileOps[F2, G, O2] =
new Stream.CompileOps[F2, G, O2](underlying)
/** Runs the supplied stream in the background as elements from this stream are pulled.
*
* The resulting stream terminates upon termination of this stream. The background stream will
* be interrupted at that point. Early termination of `that` does not terminate the resulting stream.
*
* Any errors that occur in either `this` or `that` stream result in the overall stream terminating
* with an error.
*
* Upon finalization, the resulting stream will interrupt the background stream and wait for it to be
* finalized.
*
* This method is equivalent to `this mergeHaltL that.drain`, just more efficient for `this` and `that` evaluation.
*
* @example {{{
* scala> import cats.effect.IO, cats.effect.unsafe.implicits.global
* scala> val data: Stream[IO,Int] = Stream.range(1, 10).covary[IO]
* scala> Stream.eval(fs2.concurrent.SignallingRef[IO,Int](0)).flatMap(s => Stream(s).concurrently(data.evalMap(s.set))).flatMap(_.discrete).takeWhile(_ < 9, true).compile.last.unsafeRunSync()
* res0: Option[Int] = Some(9)
* }}}
*/
def concurrently[F2[x] >: F[x], O2](
that: Stream[F2, O2]
)(implicit F: Concurrent[F2]): Stream[F2, O] = {
val fstream: F2[Stream[F2, O]] = for {
interrupt <- F.deferred[Unit]
backResult <- F.deferred[Either[Throwable, Unit]]
} yield {
def watch[A](str: Stream[F2, A]) = str.interruptWhen(interrupt.get.attempt)
val compileBack: F2[Boolean] = watch(that).compile.drain.attempt.flatMap {
// Pass the result of backstream completion in the backResult deferred.
// IF result of back-stream was failed, interrupt fore. Otherwise, let it be
case r @ Right(_) => backResult.complete(r)
case l @ Left(_) => backResult.complete(l) >> interrupt.complete(())
}
// stop background process but await for it to finalise with a result
// We use F.fromEither to bring errors from the back into the fore
val stopBack: F2[Unit] = interrupt.complete(()) >> backResult.get.flatMap(F.fromEither)
Stream.bracket(compileBack.start)(_ => stopBack) >> watch(this)
}
Stream.eval(fstream).flatten
}
/** Prepends a chunk onto the front of this stream.
*
* @example {{{
* scala> Stream(1,2,3).cons(Chunk(-1, 0)).toList
* res0: List[Int] = List(-1, 0, 1, 2, 3)
* }}}
*/
def cons[O2 >: O](c: Chunk[O2]): Stream[F, O2] =
if (c.isEmpty) this else Stream.chunk(c) ++ this
/** Prepends a chunk onto the front of this stream.
*
* @example {{{
* scala> Stream(1,2,3).consChunk(Chunk.vector(Vector(-1, 0))).toList
* res0: List[Int] = List(-1, 0, 1, 2, 3)
* }}}
*/
def consChunk[O2 >: O](c: Chunk[O2]): Stream[F, O2] =
cons(c)
/** Prepends a single value onto the front of this stream.
*
* @example {{{
* scala> Stream(1,2,3).cons1(0).toList
* res0: List[Int] = List(0, 1, 2, 3)
* }}}
*/
def cons1[O2 >: O](o: O2): Stream[F, O2] =
cons(Chunk.singleton(o))
/** Lifts this stream to the specified effect and output types.
*
* @example {{{
* scala> import cats.effect.IO
* scala> Stream.empty.covaryAll[IO,Int]
* res0: Stream[IO,Int] = Stream(..)
* }}}
*/
def covaryAll[F2[x] >: F[x], O2 >: O]: Stream[F2, O2] = this
/** Lifts this stream to the specified output type.
*
* @example {{{
* scala> Stream(Some(1), Some(2), Some(3)).covaryOutput[Option[Int]]
* res0: Stream[Pure,Option[Int]] = Stream(..)
* }}}
*/
def covaryOutput[O2 >: O]: Stream[F, O2] = this
/** Debounce the stream with a minimum period of `d` between each element.
*
* Use-case: if this is a stream of updates about external state, we may
* want to refresh (side-effectful) once every 'd' milliseconds, and every
* time we refresh we only care about the latest update.
*
* @return A stream whose values is an in-order, not necessarily strict
* subsequence of this stream, and whose evaluation will force a delay
* `d` between emitting each element. The exact subsequence would depend
* on the chunk structure of this stream, and the timing they arrive.
*
* @example {{{
* scala> import scala.concurrent.duration._, cats.effect.IO, cats.effect.unsafe.implicits.global
* scala> val s = Stream(1, 2, 3) ++ Stream.sleep_[IO](500.millis) ++ Stream(4, 5) ++ Stream.sleep_[IO](10.millis) ++ Stream(6)
* scala> val s2 = s.debounce(100.milliseconds)
* scala> s2.compile.toVector.unsafeRunSync()
* res0: Vector[Int] = Vector(3, 6)
* }}}
*/
def debounce[F2[x] >: F[x]](
d: FiniteDuration
)(implicit F: Temporal[F2]): Stream[F2, O] = Stream.force {
for {
queue <- Queue.bounded[F2, Option[O]](1)
ref <- F.ref[Option[O]](None)
} yield {
val enqueueLatest: F2[Unit] =
ref.getAndSet(None).flatMap(prev => if (prev.isEmpty) F.unit else queue.offer(prev))
def enqueueItem(o: O): F2[Unit] =
ref.getAndSet(Some(o)).flatMap {
case None => F.start(F.sleep(d) >> enqueueLatest).void
case Some(_) => F.unit
}
def go(tl: Pull[F2, O, Unit]): Pull[F2, INothing, Unit] =
Pull.uncons(tl).flatMap {
// Note: hd is non-empty, so hd.last.get is safe
case Some((hd, tl)) => Pull.eval(enqueueItem(hd.last.get)) >> go(tl)
case None => Pull.eval(enqueueLatest >> queue.offer(None))
}
val debouncedEnqueue: Stream[F2, INothing] = new Stream(go(this.underlying))
Stream.fromQueueNoneTerminated(queue).concurrently(debouncedEnqueue)
}
}
/** Throttles the stream to the specified `rate`. Unlike [[debounce]], [[metered]] doesn't drop elements.
*
* Provided `rate` should be viewed as maximum rate:
* resulting rate can't exceed the output rate of `this` stream.
*/
def metered[F2[x] >: F[x]: Temporal](rate: FiniteDuration): Stream[F2, O] =
Stream.fixedRate[F2](rate).zipRight(this)
/** Logs the elements of this stream as they are pulled.
*
* By default, `toString` is called on each element and the result is printed
* to standard out. To change formatting, supply a value for the `formatter`
* param. To change the destination, supply a value for the `logger` param.
*
* This method does not change the chunk structure of the stream. To debug the
* chunk structure, see [[debugChunks]].
*
* Logging is not done in `F` because this operation is intended for debugging,
* including pure streams.
*
* @example {{{
* scala> Stream(1, 2).append(Stream(3, 4)).debug(o => s"a: $o").toList
* a: 1
* a: 2
* a: 3
* a: 4
* res0: List[Int] = List(1, 2, 3, 4)
* }}}
*/
def debug[O2 >: O](
formatter: O2 => String = (o2: O2) => o2.toString,
logger: String => Unit = println(_)
): Stream[F, O] =
map { o =>
logger(formatter(o))
o
}
/** Like [[debug]] but logs chunks as they are pulled instead of individual elements.
*
* @example {{{
* scala> Stream(1, 2, 3).append(Stream(4, 5, 6)).debugChunks(c => s"a: $c").buffer(2).debugChunks(c => s"b: $c").toList
* a: Chunk(1, 2, 3)
* b: Chunk(1, 2)
* a: Chunk(4, 5, 6)
* b: Chunk(3, 4)
* b: Chunk(5, 6)
* res0: List[Int] = List(1, 2, 3, 4, 5, 6)
* }}}
*/
def debugChunks[O2 >: O](
formatter: Chunk[O2] => String = (os: Chunk[O2]) => os.toString,
logger: String => Unit = println(_)
): Stream[F, O] =
chunks.flatMap { os =>
logger(formatter(os))
Stream.chunk(os)
}
/** Returns a stream that when run, sleeps for duration `d` and then pulls from this stream.
*
* Alias for `sleep_[F](d) ++ this`.
*/
def delayBy[F2[x] >: F[x]: Temporal](d: FiniteDuration): Stream[F2, O] =
Stream.sleep_[F2](d) ++ this
/** Skips the first element that matches the predicate.
*
* @example {{{
* scala> Stream.range(1, 10).delete(_ % 2 == 0).toList
* res0: List[Int] = List(1, 3, 4, 5, 6, 7, 8, 9)
* }}}
*/
def delete(p: O => Boolean): Stream[F, O] =
this.pull
.takeWhile(o => !p(o))
.flatMap {
case None => Pull.done
case Some(s) => s.drop(1).pull.echo
}
.stream
/** Like [[balance]] but uses an unlimited chunk size.
*
* Alias for `through(Balance(Int.MaxValue))`.
*/
def balanceAvailable[F2[x] >: F[x]: Concurrent]: Stream[F2, Stream[F2, O]] =
through(Balance[F2, O](Int.MaxValue))
/** Returns a stream of streams where each inner stream sees an even portion of the
* elements of the source stream relative to the number of inner streams taken from
* the outer stream. For example, `src.balance(chunkSize).take(2)` results in two
* inner streams, each which see roughly half of the elements of the source stream.
*
* The `chunkSize` parameter specifies the maximum chunk size from the source stream
* that should be passed to an inner stream. For completely fair distribution of elements,
* use a chunk size of 1. For best performance, use a chunk size of `Int.MaxValue`.
*
* See [[fs2.concurrent.Balance.apply]] for more details.
*
* Alias for `through(Balance(chunkSize))`.
*/
def balance[F2[x] >: F[x]: Concurrent](
chunkSize: Int
): Stream[F2, Stream[F2, O]] =
through(Balance(chunkSize))
/** Like [[balance]] but instead of providing a stream of sources, runs each pipe.
*
* The pipes are run concurrently with each other. Hence, the parallelism factor is equal
* to the number of pipes.
* Each pipe may have a different implementation, if required; for example one pipe may
* process elements while another may send elements for processing to another machine.
*
* Each pipe is guaranteed to see all `O` pulled from the source stream, unlike `broadcast`,
* where workers see only the elements after the start of each worker evaluation.
*
* Note: the resulting stream will not emit values, even if the pipes do.
* If you need to emit `Unit` values, consider using `balanceThrough`.
*
* @param chunkSize max size of chunks taken from the source stream
* @param pipes pipes that will concurrently process the work
*/
def balanceTo[F2[x] >: F[x]: Concurrent](
chunkSize: Int
)(pipes: Pipe[F2, O, Nothing]*): Stream[F2, INothing] =
balanceThrough[F2, INothing](chunkSize)(pipes: _*)
/** Variant of `balanceTo` that broadcasts to `maxConcurrent` instances of a single pipe.
*
* @param chunkSize max size of chunks taken from the source stream
* @param maxConcurrent maximum number of pipes to run concurrently
* @param pipe pipe to use to process elements
*/
def balanceTo[F2[x] >: F[x]: Concurrent](chunkSize: Int, maxConcurrent: Int)(
pipe: Pipe[F2, O, INothing]
): Stream[F2, Unit] =
balanceThrough[F2, INothing](chunkSize, maxConcurrent)(pipe)
/** Alias for `through(Balance.through(chunkSize)(pipes)`.
*/
def balanceThrough[F2[x] >: F[x]: Concurrent, O2](
chunkSize: Int
)(pipes: Pipe[F2, O, O2]*): Stream[F2, O2] =
through(Balance.through[F2, O, O2](chunkSize)(pipes: _*))
/** Variant of `balanceThrough` that takes number of concurrency required and single pipe.
*
* @param chunkSize max size of chunks taken from the source stream
* @param maxConcurrent maximum number of pipes to run concurrently
* @param pipe pipe to use to process elements
*/
def balanceThrough[F2[x] >: F[x]: Concurrent, O2](
chunkSize: Int,
maxConcurrent: Int
)(
pipe: Pipe[F2, O, O2]
): Stream[F2, O2] =
balanceThrough[F2, O2](chunkSize)((0 until maxConcurrent).map(_ => pipe): _*)
/** Removes all output values from this stream.
*
* Often used with `merge` to run one side of the merge for its effect
* while getting outputs from the opposite side of the merge.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> Stream.eval(SyncIO(println("x"))).drain.compile.toVector.unsafeRunSync()
* res0: Vector[INothing] = Vector()
* }}}
*/
def drain: Stream[F, INothing] =
this.repeatPull(_.uncons.flatMap(uc => Pull.pure(uc.map(_._2))))
/** Drops `n` elements of the input, then echoes the rest.
*
* @example {{{
* scala> Stream.range(0,10).drop(5).toList
* res0: List[Int] = List(5, 6, 7, 8, 9)
* }}}
*/
def drop(n: Long): Stream[F, O] =
this.pull.drop(n).flatMap(_.map(_.pull.echo).getOrElse(Pull.done)).stream
/** Drops the last element.
*
* @example {{{
* scala> Stream.range(0,10).dropLast.toList
* res0: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8)
* }}}
*/
def dropLast: Stream[F, O] = dropLastIf(_ => true)
/** Drops the last element if the predicate evaluates to true.
*
* @example {{{
* scala> Stream.range(0,10).dropLastIf(_ > 5).toList
* res0: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8)
* }}}
*/
def dropLastIf(p: O => Boolean): Stream[F, O] = {
def go(last: Chunk[O], s: Stream[F, O]): Pull[F, O, Unit] =
s.pull.uncons.flatMap {
case Some((hd, tl)) =>
Pull.output(last) >> go(hd, tl)
case None =>
val o = last(last.size - 1)
if (p(o)) {
val (prefix, _) = last.splitAt(last.size - 1)
Pull.output(prefix)
} else Pull.output(last)
}
this.pull.uncons.flatMap {
case Some((hd, tl)) => go(hd, tl)
case None => Pull.done
}.stream
}
/** Outputs all but the last `n` elements of the input.
*
* This is a '''pure''' stream operation: if `s` is a finite pure stream, then `s.dropRight(n).toList`
* is equal to `this.toList.reverse.drop(n).reverse`.
*
* @example {{{
* scala> Stream.range(0,10).dropRight(5).toList
* res0: List[Int] = List(0, 1, 2, 3, 4)
* }}}
*/
def dropRight(n: Int): Stream[F, O] =
if (n <= 0) this
else {
def go(acc: Chunk[O], s: Stream[F, O]): Pull[F, O, Unit] =
s.pull.uncons.flatMap {
case None => Pull.done
case Some((hd, tl)) =>
val all = acc ++ hd
Pull.output(all.dropRight(n)) >> go(all.takeRight(n), tl)
}
go(Chunk.empty, this).stream
}
/** Like [[dropWhile]], but drops the first value which tests false.
*
* @example {{{
* scala> Stream.range(0,10).dropThrough(_ != 4).toList
* res0: List[Int] = List(5, 6, 7, 8, 9)
* }}}
*
* '''Pure:''' if `this` is a finite pure stream, then `this.dropThrough(p).toList` is equal to
* `this.toList.dropWhile(p).drop(1)`
*/
def dropThrough(p: O => Boolean): Stream[F, O] =
this.pull
.dropThrough(p)
.flatMap(_.map(_.pull.echo).getOrElse(Pull.done))
.stream
/** Drops elements from the head of this stream until the supplied predicate returns false.
*
* @example {{{
* scala> Stream.range(0,10).dropWhile(_ != 4).toList
* res0: List[Int] = List(4, 5, 6, 7, 8, 9)
* }}}
*
* '''Pure''' this operation maps directly to `List.dropWhile`
*/
def dropWhile(p: O => Boolean): Stream[F, O] =
this.pull
.dropWhile(p)
.flatMap(_.map(_.pull.echo).getOrElse(Pull.done))
.stream
/** Like `[[merge]]`, but tags each output with the branch it came from.
*
* @example {{{
* scala> import scala.concurrent.duration._, cats.effect.IO, cats.effect.unsafe.implicits.global
* scala> val s1 = Stream.awakeEvery[IO](1000.millis).scan(0)((acc, _) => acc + 1)
* scala> val s = s1.either(Stream.sleep_[IO](500.millis) ++ s1).take(10)
* scala> s.take(10).compile.toVector.unsafeRunSync()
* res0: Vector[Either[Int,Int]] = Vector(Left(0), Right(0), Left(1), Right(1), Left(2), Right(2), Left(3), Right(3), Left(4), Right(4))
* }}}
*/
def either[F2[x] >: F[x]: Concurrent, O2](
that: Stream[F2, O2]
): Stream[F2, Either[O, O2]] =
map(Left(_)).merge(that.map(Right(_)))
/** Enqueues the elements of this stream to the supplied queue.
*/
def enqueueUnterminated[F2[x] >: F[x], O2 >: O](queue: Queue[F2, O2]): Stream[F2, Nothing] =
this.foreach(queue.offer)
/** Enqueues the chunks of this stream to the supplied queue.
*/
def enqueueUnterminatedChunks[F2[x] >: F[x], O2 >: O](
queue: Queue[F2, Chunk[O2]]
): Stream[F2, Nothing] =
this.chunks.foreach(queue.offer)
/** Enqueues the elements of this stream to the supplied queue and enqueues `None` when this stream terminates.
*/
def enqueueNoneTerminated[F2[x] >: F[x], O2 >: O](
queue: Queue[F2, Option[O2]]
): Stream[F2, Nothing] =
this.noneTerminate.foreach(queue.offer)
/** Enqueues the chunks of this stream to the supplied queue and enqueues `None` when this stream terminates.
*/
def enqueueNoneTerminatedChunks[F2[x] >: F[x], O2 >: O](
queue: Queue[F2, Option[Chunk[O2]]]
): Stream[F2, Nothing] =
this.chunks.noneTerminate.foreach(queue.offer)
/** Alias for `flatMap(o => Stream.eval(f(o)))`.
*
* @example {{{
* scala> import cats.effect.SyncIO
* scala> Stream(1,2,3,4).evalMap(i => SyncIO(println(i))).compile.drain.unsafeRunSync()
* res0: Unit = ()
* }}}
*
* Note this operator will de-chunk the stream back into chunks of size 1,
* which has performance implications. For maximum performance, `evalMapChunk`
* is available, however, with caveats.
*/
def evalMap[F2[x] >: F[x], O2](f: O => F2[O2]): Stream[F2, O2] =
flatMap(o => Stream.eval(f(o)))
/** Like `evalMap`, but operates on chunks for performance. This means this operator
* is not lazy on every single element, rather on the chunks.
*
* For instance, `evalMap` would only print twice in the follow example (note the `take(2)`):
* @example {{{
* scala> import cats.effect.SyncIO
* scala> Stream(1,2,3,4).evalMap(i => SyncIO(println(i))).take(2).compile.drain.unsafeRunSync()
* res0: Unit = ()
* }}}
*
* But with `evalMapChunk`, it will print 4 times:
* @example {{{
* scala> Stream(1,2,3,4).evalMapChunk(i => SyncIO(println(i))).take(2).compile.drain.unsafeRunSync()