File: stream.go

package info (click to toggle)
golang-github-bradenaw-juniper 0.15.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 872 kB
  • sloc: sh: 27; makefile: 2
file content (1036 lines) | stat: -rw-r--r-- 24,662 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
// Package stream allows iterating over sequences of values where iteration may fail, for example
// when it involves I/O.
package stream

import (
	"context"
	"errors"
	"sync"
	"sync/atomic"
	"time"

	"github.com/bradenaw/juniper/iterator"
	"github.com/bradenaw/juniper/xmath"
)

var (
	// End is returned from Stream.Next when iteration ends successfully.
	End = errors.New("end of stream")
	// ErrClosedPipe is returned from PipeSender.Send() when the associated stream has already been
	// closed.
	ErrClosedPipe = errors.New("closed pipe")
	// ErrMoreThanOne is returned from One when a Stream yielded more than one item.
	ErrMoreThanOne = errors.New("stream had more than one item")
	// ErrEmpty is returned from One when a Stream yielded no items.
	ErrEmpty = errors.New("stream empty")
)

// Stream is used to iterate over a sequence of values. It is similar to Iterator, except intended
// for use when iteration may fail for some reason, usually because the sequence requires I/O to
// produce.
//
// Streams and the combinator functions are lazy, meaning they do no work until a call to Next().
//
// Streams do not need to be fully consumed, but streams must be closed. Functions in this package
// that are passed streams expect to be the sole user of that stream going forward, and so will
// handle closing on your behalf so long as all streams they return are closed appropriately.
type Stream[T any] interface {
	// Next advances the stream and returns the next item. If the stream is already over, Next
	// returns stream.End in the second return. Note that the final item of the stream has nil in
	// the second return, and it's the following call that returns stream.End.
	//
	// Once a Next call returns stream.End, it is expected that the Stream will return stream.End to
	// every Next call afterwards.
	Next(ctx context.Context) (T, error)
	// Close ends receiving from the stream. It is invalid to call Next after calling Close.
	Close()
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Converters + Constructors                                                                      //
// Functions that produce a Stream.                                                               //
////////////////////////////////////////////////////////////////////////////////////////////////////

// Chan returns a Stream that receives values from c.
func Chan[T any](c <-chan T) Stream[T] {
	return &chanStream[T]{c: c}
}

type chanStream[T any] struct {
	c <-chan T
}

func (s *chanStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	select {
	case item, ok := <-s.c:
		if !ok {
			return zero, End
		}
		return item, nil
	case <-ctx.Done():
		return zero, ctx.Err()
	}
}

func (s *chanStream[T]) Close() {}

// Empty returns a Stream that yields stream.End immediately.
func Empty[T any]() Stream[T] {
	return emptyStream[T]{}
}

type emptyStream[T any] struct{}

func (s emptyStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	return zero, End
}

func (s emptyStream[T]) Close() {}

// Error returns a Stream that immediately produces err from Next.
func Error[T any](err error) Stream[T] {
	return errorStream[T]{err}
}

type errorStream[T any] struct {
	err error
}

func (s errorStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	return zero, s.err
}

func (s errorStream[T]) Close() {}

// FromIterator returns a Stream that yields the values from iter. This stream ignores the context
// passed to Next during the call to iter.Next.
func FromIterator[T any](iter iterator.Iterator[T]) Stream[T] {
	return &iteratorStream[T]{iter: iter}
}

type iteratorStream[T any] struct {
	iter iterator.Iterator[T]
}

func (s *iteratorStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	if ctx.Err() != nil {
		return zero, ctx.Err()
	}
	item, ok := s.iter.Next()
	if !ok {
		return zero, End
	}
	return item, nil
}

func (s *iteratorStream[T]) Close() {}

// Pipe returns a linked sender and receiver pair. Values sent using sender.Send will be delivered
// to the given Stream. The Stream will terminate when the sender is closed.
//
// bufferSize is the number of elements in the buffer between the sender and the receiver. 0 has the
// same meaning as for the built-in make(chan).
func Pipe[T any](bufferSize int) (*PipeSender[T], Stream[T]) {
	c := make(chan T, bufferSize)
	senderDone := make(chan struct{})
	senderErr := new(error)
	streamDone := make(chan struct{})

	sender := &PipeSender[T]{
		c:          c,
		senderErr:  senderErr,
		senderDone: senderDone,
		streamDone: streamDone,
	}
	receiver := &pipeStream[T]{
		c:          c,
		senderErr:  senderErr,
		senderDone: senderDone,
		streamDone: streamDone,
	}

	return sender, receiver
}

// PipeSender is the send half of a pipe returned by Pipe.
type PipeSender[T any] struct {
	c          chan<- T
	senderErr  *error
	senderDone chan struct{}
	streamDone <-chan struct{}
}

// Send attempts to send x to the receiver. If the receiver closes before x can be sent, returns
// ErrClosedPipe immediately. If ctx expires before x can be sent, returns ctx.Err().
//
// A nil return does not necessarily mean that the receiver will see x, since the receiver may close
// early.
//
// Send may be called concurrently with other Sends and with Close.
func (s *PipeSender[T]) Send(ctx context.Context, x T) error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-s.streamDone:
		return ErrClosedPipe
	case <-s.senderDone:
		return *s.senderErr
	case s.c <- x:
		return nil
	}
}

// TrySend attempts to send x to the receiver, but returns (false, nil) if the pipe's buffer is
// already full instead of blocking. If the receiver is already closed, returns ErrClosedPipe. If
// ctx expires before x can be sent, returns ctx.Err().
//
// A (true, nil) return does not necessarily mean that the receiver will see x, since the receiver
// may close early.
//
// TrySend may be called concurrently with other Sends and with Close.
func (s *PipeSender[T]) TrySend(ctx context.Context, x T) (bool, error) {
	select {
	case <-ctx.Done():
		return false, ctx.Err()
	case <-s.streamDone:
		return false, ErrClosedPipe
	case <-s.senderDone:
		return false, *s.senderErr
	default:
	}
	select {
	case s.c <- x:
		return true, nil
	default:
		return false, nil
	}
}

// Close closes the PipeSender, signalling to the receiver that no more values will be sent. If an
// error is provided, it will surface to the receiver's Next and to any concurrent Sends.
//
// Close may only be called once.
func (s *PipeSender[T]) Close(err error) {
	*s.senderErr = err
	close(s.senderDone)
}

type pipeStream[T any] struct {
	c          <-chan T
	senderErr  *error
	senderDone <-chan struct{}
	streamDone chan<- struct{}
}

func (s *pipeStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	select {
	case <-ctx.Done():
		return zero, ctx.Err()
	case item := <-s.c:
		return item, nil
	case <-s.senderDone:
		err := *s.senderErr
		if err != nil {
			return zero, err
		}
		return zero, End
	}
}

func (s *pipeStream[T]) Close() { close(s.streamDone) }

// Peekable allows viewing the next item from a stream without consuming it.
type Peekable[T any] interface {
	Stream[T]
	// Peek returns the next item of the stream if there is one without consuming it.
	//
	// If Peek returns a value, the next call to Next will return the same value.
	Peek(ctx context.Context) (T, error)
}

// WithPeek returns iter with a Peek() method attached.
func WithPeek[T any](s Stream[T]) Peekable[T] {
	return &peekable[T]{inner: s, has: false}
}

type peekable[T any] struct {
	inner Stream[T]
	curr  T
	has   bool
}

func (s *peekable[T]) Next(ctx context.Context) (T, error) {
	if s.has {
		item := s.curr
		s.has = false
		var zero T
		s.curr = zero
		return item, nil
	}
	return s.inner.Next(ctx)
}
func (s *peekable[T]) Peek(ctx context.Context) (T, error) {
	var zero T
	if !s.has {
		var err error
		s.curr, err = s.inner.Next(ctx)
		if err == End {
			s.has = false
			return zero, End
		} else if err != nil {
			return zero, err
		}
		s.has = true
	}
	return s.curr, nil
}
func (s *peekable[T]) Close() {
	s.inner.Close()
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Reducers                                                                                       //
// Functions that consume a stream and produce some kind of final value.                          //
////////////////////////////////////////////////////////////////////////////////////////////////////

// Collect advances s to the end and returns all of the items seen as a slice.
func Collect[T any](ctx context.Context, s Stream[T]) ([]T, error) {
	defer s.Close()

	var out []T
	for {
		item, err := s.Next(ctx)
		if err == End {
			return out, nil
		} else if err != nil {
			return nil, err
		}
		out = append(out, item)
	}
}

// Last consumes s and returns the last n items. If s yields fewer than n items, Last returns
// all of them.
func Last[T any](ctx context.Context, s Stream[T], n int) ([]T, error) {
	defer s.Close()
	buf := make([]T, n)
	i := 0
	for {
		item, err := s.Next(ctx)
		if err == End {
			break
		} else if err != nil {
			return nil, err
		}
		buf[i%n] = item
		i++
	}
	if i < n {
		return buf[:i], nil
	}
	out := make([]T, n)
	idx := i % n
	copy(out, buf[idx:])
	copy(out[n-idx:], buf[:idx])
	return out, nil
}

// One returns the only item that s yields. Returns an error if encountered, or if s yields zero or
// more than one item.
func One[T any](ctx context.Context, s Stream[T]) (T, error) {
	var zero T
	x, err := s.Next(ctx)
	if err == End {
		return zero, ErrEmpty
	} else if err != nil {
		return zero, err
	}
	_, err = s.Next(ctx)
	if err == End {
		return x, nil
	} else if err != nil {
		return zero, err
	}
	return zero, ErrMoreThanOne
}

// Reduce reduces s to a single value using the reduction function f.
func Reduce[T any, U any](
	ctx context.Context,
	s Stream[T],
	initial U,
	f func(U, T) (U, error),
) (U, error) {
	defer s.Close()

	acc := initial
	for {
		item, err := s.Next(ctx)
		if err == End {
			return acc, nil
		} else if err != nil {
			return acc, err
		}
		acc, err = f(acc, item)
		if err != nil {
			return acc, err
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Combinators                                                                                    //
// Functions that take and return iterators, transforming the output somehow.                     //
////////////////////////////////////////////////////////////////////////////////////////////////////

// Batch returns a stream of non-overlapping batches from s of size batchSize. Batch is similar to
// Chunk with the added feature that an underfilled batch will be delivered to the output stream if
// any item has been in the batch for more than maxWait.
func Batch[T any](s Stream[T], maxWait time.Duration, batchSize int) Stream[[]T] {
	return BatchFunc(s, maxWait, func(batch []T) bool {
		return len(batch) >= batchSize
	})
}

// BatchFunc returns a stream of non-overlapping batches from s, using full to determine when a
// batch is full. BatchFunc is similar to Chunk with the added feature that an underfilled batch
// will be delivered to the output stream if any item has been in the batch for more than maxWait.
func BatchFunc[T any](
	s Stream[T],
	maxWait time.Duration,
	full func(batch []T) bool,
) Stream[[]T] {
	bgCtx, bgCancel := context.WithCancel(context.Background())

	out := &batchStream[T]{
		batchC:   make(chan []T),
		waiting:  make(chan struct{}),
		bgCancel: bgCancel,
	}

	c := make(chan T)

	out.wg.Add(2)

	go func() {
		defer out.wg.Done()
		defer s.Close()
		defer close(c)

		for {
			item, err := s.Next(bgCtx)
			if err == End {
				break
			} else if err == context.Canceled && bgCtx.Err() == context.Canceled {
				break
			} else if err != nil {
				out.err = err
				return
			}
			c <- item
		}
	}()

	// Build up batches and flush them when either:
	// A) The batch is full.
	// B) It's been at least maxWait since the first item arrived _and_ there is somebody waiting.
	// No sense in underfilling a batch if nobody's actually asking for it yet.
	// C) There aren't any more items.
	go func() {
		defer out.wg.Done()

		var batch []T
		var batchStart time.Time
		batchSizeEstimate := 0
		var timer *time.Timer
		// Starts off as nil so that the timerC select arm isn't chosen until populated.  Also set
		// to nil when we've already stopped or received from timer to know when it needs to be
		// drained.
		var timerC <-chan time.Time
		waitingAtEmpty := false

		defer func() {
			if timer != nil {
				timer.Stop()
			}
			close(out.batchC)
		}()

		flush := func() bool {
			select {
			case <-bgCtx.Done():
				return false
			case out.batchC <- batch:
			}
			batchSizeEstimate = (batchSizeEstimate + len(batch)) / 2
			batch = make([]T, 0, xmath.Max(len(batch), batchSizeEstimate*11/10))
			waitingAtEmpty = false
			return true
		}

		stopTimer := func() {
			if timer == nil {
				return
			}
			stopped := timer.Stop()
			if !stopped && timerC != nil {
				<-timerC
			}
			timerC = nil
		}

		startTimer := func() {
			stopTimer()
			if timer == nil {
				timer = time.NewTimer(maxWait - time.Since(batchStart))
			} else {
				timer.Reset(maxWait - time.Since(batchStart))
			}
			timerC = timer.C
		}

		for {
			select {
			case item, ok := <-c:
				if !ok { // Case (C): we're done.
					// Flush what we have so far, if any.
					if len(batch) > 0 {
						_ = flush()
					}
					return
				}
				batch = append(batch, item)
				if full(batch) { // Case (A): the batch is full.
					stopTimer()
					if !flush() {
						return
					}
				}
				if len(batch) == 1 { // Bookkeeping for case (B).
					batchStart = time.Now()
					if waitingAtEmpty {
						startTimer()
					}
				}
			case <-timerC: // Case (B).
				timerC = nil
				// Being here already implies the conditions are true, since the timer is only
				// running while the batch is non-empty and there's somebody waiting.
				if !flush() {
					return
				}
			case <-out.waiting: // Bookkeeping for case (B).
				if len(batch) > 0 {
					// Time already elapsed, just deliver the batch now.
					if time.Since(batchStart) > maxWait {
						if !flush() {
							return
						}
					} else {
						startTimer()
					}
				} else {
					// Timer will start when the first item shows up.
					waitingAtEmpty = true
				}
			}
		}
	}()

	return out
}

type batchStream[T any] struct {
	bgCancel context.CancelFunc
	wg       sync.WaitGroup
	batchC   chan []T
	// populated at most once and always before batchC closes
	err     error
	waiting chan struct{}
}

func (iter *batchStream[T]) Next(ctx context.Context) ([]T, error) {
	select {
	// There might be a batch already ready because it filled before we even asked.
	case batch, ok := <-iter.batchC:
		if !ok {
			if iter.err != nil {
				return nil, iter.err
			}
			return nil, End
		}
		return batch, nil
	// Otherwise, we need to let the sender know we're waiting so that they can flush an underfilled
	// batch at interval.
	case iter.waiting <- struct{}{}:
		select {
		case batch, ok := <-iter.batchC:
			if !ok {
				if iter.err != nil {
					return nil, iter.err
				}
				return nil, End
			}
			return batch, nil
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

func (iter *batchStream[T]) Close() {
	iter.bgCancel()
	iter.wg.Wait()
}

// Chunk returns a stream of non-overlapping chunks from s of size chunkSize. The last chunk will be
// smaller than chunkSize if the stream does not contain an even multiple.
func Chunk[T any](s Stream[T], chunkSize int) Stream[[]T] {
	return &chunkStream[T]{
		inner:     s,
		chunkSize: chunkSize,
	}
}

type chunkStream[T any] struct {
	inner     Stream[T]
	chunkSize int
	chunk     []T
}

func (s *chunkStream[T]) Next(ctx context.Context) ([]T, error) {
	for {
		item, err := s.inner.Next(ctx)
		if err == End {
			break
		} else if err != nil {
			return nil, err
		}
		s.chunk = append(s.chunk, item)
		if len(s.chunk) == s.chunkSize {
			chunk := s.chunk
			s.chunk = make([]T, 0, s.chunkSize)
			return chunk, nil
		}
	}
	if len(s.chunk) > 0 {
		chunk := s.chunk
		s.chunk = make([]T, 0, s.chunkSize)
		return chunk, nil
	}
	return nil, End
}

func (s *chunkStream[T]) Close() {
	s.inner.Close()
}

// Compact elides adjacent duplicates from s.
func Compact[T comparable](s Stream[T]) Stream[T] {
	return CompactFunc(s, func(a, b T) bool {
		return a == b
	})
}

// CompactFunc elides adjacent duplicates from s, using eq to determine duplicates.
func CompactFunc[T any](s Stream[T], eq func(T, T) bool) Stream[T] {
	return &compactStream[T]{
		inner: s,
		first: true,
		eq:    eq,
	}
}

type compactStream[T any] struct {
	inner Stream[T]
	prev  T
	first bool
	eq    func(T, T) bool
}

func (s *compactStream[T]) Next(ctx context.Context) (T, error) {
	for {
		item, err := s.inner.Next(ctx)
		if err != nil {
			return item, err
		}

		if s.first {
			s.first = false
			s.prev = item
			return item, nil
		} else if !s.eq(s.prev, item) {
			s.prev = item
			return item, nil
		}
	}
}

func (s *compactStream[T]) Close() {
	s.inner.Close()
}

// Filter returns a Stream that yields only the items from s for which keep returns true. If keep
// returns an error, terminates the stream early.
func Filter[T any](s Stream[T], keep func(context.Context, T) (bool, error)) Stream[T] {
	return &filterStream[T]{inner: s, keep: keep}
}

type filterStream[T any] struct {
	inner Stream[T]
	keep  func(context.Context, T) (bool, error)
}

func (s *filterStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	for {
		item, err := s.inner.Next(ctx)
		if err != nil {
			return zero, err
		}
		ok, err := s.keep(ctx, item)
		if err != nil {
			return zero, err
		}
		if ok {
			return item, nil
		}
	}
}

func (s *filterStream[T]) Close() {
	s.inner.Close()
}

// First returns a Stream that yields the first n items from s.
func First[T any](s Stream[T], n int) Stream[T] {
	return &firstStream[T]{inner: s, x: n}
}

type firstStream[T any] struct {
	inner Stream[T]
	x     int
}

func (s *firstStream[T]) Next(ctx context.Context) (T, error) {
	if s.x <= 0 {
		var zero T
		return zero, End
	}
	item, err := s.inner.Next(ctx)
	if err != nil {
		return item, err
	}
	s.x--
	return item, nil
}

func (s *firstStream[T]) Close() {
	s.inner.Close()
}

// Flatten returns a stream that yields all items from all streams yielded by s.
func Flatten[T any](s Stream[Stream[T]]) Stream[T] {
	return &flattenStream[T]{inner: s}
}

type flattenStream[T any] struct {
	inner Stream[Stream[T]]
	curr  Stream[T]
}

func (s *flattenStream[T]) Next(ctx context.Context) (T, error) {
	for {
		if s.curr == nil {
			var err error
			s.curr, err = s.inner.Next(ctx)
			if err != nil {
				var zero T
				return zero, err
			}
		}

		item, err := s.curr.Next(ctx)
		if err == End {
			s.curr.Close()
			s.curr = nil
			continue
		} else if err != nil {
			return item, err
		}

		return item, nil
	}
}

func (s *flattenStream[T]) Close() {
	if s.curr != nil {
		s.curr.Close()
	}
	s.inner.Close()
}

func FlattenSlices[T any](s Stream[[]T]) Stream[T] {
	return &flattenSlicesStream[T]{
		inner: s,
	}
}

type flattenSlicesStream[T any] struct {
	inner  Stream[[]T]
	buffer []T
}

func (s *flattenSlicesStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	for {
		if len(s.buffer) > 0 {
			item := s.buffer[0]
			s.buffer[0] = zero
			s.buffer = s.buffer[1:]
			return item, nil
		}

		var err error
		s.buffer, err = s.inner.Next(ctx)
		if err != nil {
			return zero, err
		}
	}
}

func (s *flattenSlicesStream[T]) Close() { s.inner.Close() }

// Join returns a Stream that yields all elements from streams[0], then all elements from
// streams[1], and so on.
func Join[T any](streams ...Stream[T]) Stream[T] {
	return &joinStream[T]{remaining: streams}
}

type joinStream[T any] struct {
	remaining []Stream[T]
}

func (s *joinStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	for len(s.remaining) > 0 {
		item, err := s.remaining[0].Next(ctx)
		if err == End {
			s.remaining[0].Close()
			s.remaining = s.remaining[1:]
			continue
		} else if err != nil {
			return zero, err
		}
		return item, nil
	}
	return zero, End
}

func (s *joinStream[T]) Close() {
	for i := range s.remaining {
		s.remaining[i].Close()
	}
}

// Map transforms the values of s using the conversion f. If f returns an error, terminates the
// stream early.
func Map[T any, U any](s Stream[T], f func(context.Context, T) (U, error)) Stream[U] {
	return &mapStream[T, U]{inner: s, f: f}
}

type mapStream[T any, U any] struct {
	inner Stream[T]
	f     func(context.Context, T) (U, error)
}

func (s *mapStream[T, U]) Next(ctx context.Context) (U, error) {
	var zero U
	item, err := s.inner.Next(ctx)
	if err != nil {
		return zero, err
	}
	mapped, err := s.f(ctx, item)
	if err != nil {
		return zero, err
	}
	return mapped, nil
}

func (s *mapStream[T, U]) Close() {
	s.inner.Close()
}

// Merge merges the in streams, returning a stream that yields all elements from all of them as they
// arrive.
func Merge[T any](in ...Stream[T]) Stream[T] {
	sender, receiver := Pipe[T](0)
	nDone := uint32(0)
	closeOnce := uint32(0)
	ctx, cancel := context.WithCancel(context.Background())
	for i := 0; i < len(in); i++ {
		i := i
		go func() {
			defer func() {
				if int(atomic.AddUint32(&nDone, 1)) == len(in) &&
					atomic.LoadUint32(&closeOnce) == 0 {
					sender.Close(nil)
				}
			}()
			for {
				item, err := in[i].Next(ctx)
				if err == End {
					return
				} else if err != nil {
					if atomic.CompareAndSwapUint32(&closeOnce, 0, 1) {
						cancel()
						sender.Close(err)
					}
					return
				}
				err = sender.Send(ctx, item)
				if err != nil {
					// Implies ctx has expired or the receiver closed, either way we're done.
					return
				}
			}
		}()
	}
	return receiver
}

type mergeStream[T any] struct {
	inner  Stream[T]
	cancel func()
}

func (s *mergeStream[T]) Next(ctx context.Context) (T, error) {
	return s.inner.Next(ctx)
}

func (s *mergeStream[T]) Close() {
	s.inner.Close()
	s.cancel()
}

// Runs returns a stream of streams. The inner streams yield contiguous elements from s such that
// same(a, b) returns true for any a and b in the run.
//
// The inner stream should be drained before calling Next on the outer stream.
//
// same(a, a) must return true. If same(a, b) and same(b, c) both return true, then same(a, c) must
// also.
func Runs[T any](s Stream[T], same func(a, b T) bool) Stream[Stream[T]] {
	return &runsStream[T]{
		inner: WithPeek(s),
		same:  same,
		curr:  nil,
	}
}

type runsStream[T any] struct {
	inner Peekable[T]
	same  func(a, b T) bool
	curr  *runsInnerStream[T]
}

func (s *runsStream[T]) Next(ctx context.Context) (Stream[T], error) {
	if s.curr != nil {
		for {
			_, err := s.curr.Next(ctx)
			if err == End {
				break
			} else if err != nil {
				return nil, err
			}
		}
		s.curr.Close()
		s.curr = nil
	}
	item, err := s.inner.Peek(ctx)
	if err != nil {
		return nil, err
	}
	s.curr = &runsInnerStream[T]{parent: s, prev: item}
	return s.curr, nil
}

func (s *runsStream[T]) Close() {
	s.inner.Close()
}

type runsInnerStream[T any] struct {
	parent *runsStream[T]
	prev   T
}

func (s *runsInnerStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	if s.parent == nil {
		return zero, End
	}
	item, err := s.parent.inner.Peek(ctx)
	if err == End {
		return zero, End
	} else if err != nil {
		return zero, err
	} else if !s.parent.same(s.prev, item) {
		return zero, End
	}
	return s.parent.inner.Next(ctx)
}

func (s *runsInnerStream[T]) Close() { s.parent = nil }

// While returns a Stream that terminates before the first item from s for which f returns false.
// If f returns an error, terminates the stream early.
func While[T any](s Stream[T], f func(context.Context, T) (bool, error)) Stream[T] {
	return &whileStream[T]{
		inner: s,
		f:     f,
	}
}

type whileStream[T any] struct {
	inner Stream[T]
	f     func(context.Context, T) (bool, error)
	item  T
	has   bool
	done  bool
}

func (s *whileStream[T]) Next(ctx context.Context) (T, error) {
	var zero T
	if s.done {
		return zero, End
	}
	if !s.has {
		var err error
		s.item, err = s.inner.Next(ctx)
		if err != nil {
			return zero, err
		}
		s.has = true
	}
	ok, err := s.f(ctx, s.item)
	if err != nil {
		return zero, err
	}
	if !ok {
		s.done = true
		return zero, End
	}
	s.has = false
	return s.item, nil
}

func (s *whileStream[T]) Close() {
	s.inner.Close()
}