forked from dotnet/reactive
/
Zip.cs
731 lines (613 loc) · 23 KB
/
Zip.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Threading;
namespace System.Reactive.Linq.ObservableImpl
{
#region Binary
internal static class Zip<TFirst, TSecond, TResult>
{
internal sealed class Observable : Producer<TResult, Observable._>
{
private readonly IObservable<TFirst> _first;
private readonly IObservable<TSecond> _second;
private readonly Func<TFirst, TSecond, TResult> _resultSelector;
public Observable(IObservable<TFirst> first, IObservable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
_first = first;
_second = second;
_resultSelector = resultSelector;
}
protected override _ CreateSink(IObserver<TResult> observer) => new _(_resultSelector, observer);
protected override void Run(_ sink) => sink.Run(_first, _second);
internal sealed class _ : IdentitySink<TResult>
{
private readonly Func<TFirst, TSecond, TResult> _resultSelector;
private readonly object _gate;
private readonly FirstObserver _firstObserver;
private IDisposable _firstDisposable;
private readonly SecondObserver _secondObserver;
private IDisposable _secondDisposable;
public _(Func<TFirst, TSecond, TResult> resultSelector, IObserver<TResult> observer)
: base(observer)
{
_gate = new object();
_firstObserver = new FirstObserver(this);
_secondObserver = new SecondObserver(this);
_firstObserver.Other = _secondObserver;
_secondObserver.Other = _firstObserver;
_resultSelector = resultSelector;
}
public void Run(IObservable<TFirst> first, IObservable<TSecond> second)
{
Disposable.SetSingle(ref _firstDisposable, first.SubscribeSafe(_firstObserver));
Disposable.SetSingle(ref _secondDisposable, second.SubscribeSafe(_secondObserver));
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Disposable.TryDispose(ref _firstDisposable);
Disposable.TryDispose(ref _secondDisposable);
// clearing the queue should happen under the lock
// as they are plain Queue<T>s, not concurrent queues.
lock (_gate)
{
_firstObserver.Dispose();
_secondObserver.Dispose();
}
}
base.Dispose(disposing);
}
private sealed class FirstObserver : IObserver<TFirst>, IDisposable
{
private readonly _ _parent;
private SecondObserver _other;
private readonly Queue<TFirst> _queue;
public FirstObserver(_ parent)
{
_parent = parent;
_queue = new Queue<TFirst>();
}
public SecondObserver Other { set { _other = value; } }
public Queue<TFirst> Queue => _queue;
public bool Done { get; private set; }
public void OnNext(TFirst value)
{
lock (_parent._gate)
{
if (_other.Queue.Count > 0)
{
var r = _other.Queue.Dequeue();
TResult res;
try
{
res = _parent._resultSelector(value, r);
}
catch (Exception ex)
{
_parent.ForwardOnError(ex);
return;
}
_parent.ForwardOnNext(res);
}
else
{
if (_other.Done)
{
_parent.ForwardOnCompleted();
return;
}
_queue.Enqueue(value);
}
}
}
public void OnError(Exception error)
{
lock (_parent._gate)
{
_parent.ForwardOnError(error);
}
}
public void OnCompleted()
{
lock (_parent._gate)
{
Done = true;
if (_other.Done)
{
_parent.ForwardOnCompleted();
}
else
{
Disposable.TryDispose(ref _parent._firstDisposable);
}
}
}
public void Dispose()
{
_queue.Clear();
}
}
private sealed class SecondObserver : IObserver<TSecond>, IDisposable
{
private readonly _ _parent;
private FirstObserver _other;
private readonly Queue<TSecond> _queue;
public SecondObserver(_ parent)
{
_parent = parent;
_queue = new Queue<TSecond>();
}
public FirstObserver Other { set { _other = value; } }
public Queue<TSecond> Queue => _queue;
public bool Done { get; private set; }
public void OnNext(TSecond value)
{
lock (_parent._gate)
{
if (_other.Queue.Count > 0)
{
var l = _other.Queue.Dequeue();
TResult res;
try
{
res = _parent._resultSelector(l, value);
}
catch (Exception ex)
{
_parent.ForwardOnError(ex);
return;
}
_parent.ForwardOnNext(res);
}
else
{
if (_other.Done)
{
_parent.ForwardOnCompleted();
return;
}
_queue.Enqueue(value);
}
}
}
public void OnError(Exception error)
{
lock (_parent._gate)
{
_parent.ForwardOnError(error);
}
}
public void OnCompleted()
{
lock (_parent._gate)
{
Done = true;
if (_other.Done)
{
_parent.ForwardOnCompleted();
}
else
{
Disposable.TryDispose(ref _parent._secondDisposable);
}
}
}
public void Dispose()
{
_queue.Clear();
}
}
}
}
internal sealed class Enumerable : Producer<TResult, Enumerable._>
{
private readonly IObservable<TFirst> _first;
private readonly IEnumerable<TSecond> _second;
private readonly Func<TFirst, TSecond, TResult> _resultSelector;
public Enumerable(IObservable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
_first = first;
_second = second;
_resultSelector = resultSelector;
}
protected override _ CreateSink(IObserver<TResult> observer) => new _(_resultSelector, observer);
protected override void Run(_ sink) => sink.Run(_first, _second);
internal sealed class _ : Sink<TFirst, TResult>
{
private readonly Func<TFirst, TSecond, TResult> _resultSelector;
public _(Func<TFirst, TSecond, TResult> resultSelector, IObserver<TResult> observer)
: base(observer)
{
_resultSelector = resultSelector;
}
int _enumerationInProgress;
private IEnumerator<TSecond> _rightEnumerator;
private static readonly IEnumerator<TSecond> DisposedEnumerator = MakeDisposedEnumerator();
private static IEnumerator<TSecond> MakeDisposedEnumerator()
{
yield break;
}
public void Run(IObservable<TFirst> first, IEnumerable<TSecond> second)
{
//
// Notice the evaluation order of obtaining the enumerator and subscribing to the
// observable sequence is reversed compared to the operator's signature. This is
// required to make sure the enumerator is available as soon as the observer can
// be called. Otherwise, we end up having a race for the initialization and use
// of the _rightEnumerator field.
//
try
{
var enumerator = second.GetEnumerator();
if (Interlocked.CompareExchange(ref _rightEnumerator, enumerator, null) != null)
{
enumerator.Dispose();
return;
}
}
catch (Exception exception)
{
ForwardOnError(exception);
return;
}
Run(first);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (Interlocked.Increment(ref _enumerationInProgress) == 1)
{
Interlocked.Exchange(ref _rightEnumerator, DisposedEnumerator)?.Dispose();
}
}
base.Dispose(disposing);
}
public override void OnNext(TFirst value)
{
var currentEnumerator = Volatile.Read(ref _rightEnumerator);
if (currentEnumerator == DisposedEnumerator)
{
return;
}
if (Interlocked.Increment(ref _enumerationInProgress) != 1)
{
return;
}
bool hasNext;
TSecond right = default;
var wasDisposed = false;
try
{
try
{
hasNext = currentEnumerator.MoveNext();
if (hasNext)
{
right = currentEnumerator.Current;
}
}
finally
{
if (Interlocked.Decrement(ref _enumerationInProgress) != 0)
{
Interlocked.Exchange(ref _rightEnumerator, DisposedEnumerator)?.Dispose();
wasDisposed = true;
}
}
}
catch (Exception ex)
{
ForwardOnError(ex);
return;
}
if (wasDisposed)
{
return;
}
if (hasNext)
{
TResult result;
try
{
result = _resultSelector(value, right);
}
catch (Exception ex)
{
ForwardOnError(ex);
return;
}
ForwardOnNext(result);
}
else
{
ForwardOnCompleted();
}
}
}
}
}
#endregion
#region [3,16]-ary
#region Helpers for n-ary overloads
internal interface IZip
{
void Next(int index);
void Fail(Exception error);
void Done(int index);
}
internal abstract class ZipSink<TResult> : IdentitySink<TResult>, IZip
{
protected readonly object _gate;
private readonly ICollection[] _queues;
private readonly bool[] _isDone;
protected ZipSink(int arity, IObserver<TResult> observer)
: base(observer)
{
_gate = new object();
_isDone = new bool[arity];
_queues = new ICollection[arity];
}
public ICollection[] Queues => _queues;
public void Next(int index)
{
var hasValueAll = true;
foreach (var queue in _queues)
{
if (queue.Count == 0)
{
hasValueAll = false;
break;
}
}
if (hasValueAll)
{
TResult res;
try
{
res = GetResult();
}
catch (Exception ex)
{
ForwardOnError(ex);
return;
}
ForwardOnNext(res);
}
else
{
var allOthersDone = true;
for (var i = 0; i < _isDone.Length; i++)
{
if (i != index && !_isDone[i])
{
allOthersDone = false;
break;
}
}
if (allOthersDone)
{
ForwardOnCompleted();
}
}
}
protected abstract TResult GetResult();
public void Fail(Exception error)
{
ForwardOnError(error);
}
public void Done(int index)
{
_isDone[index] = true;
var allDone = true;
foreach (var isDone in _isDone)
{
if (!isDone)
{
allDone = false;
break;
}
}
if (allDone)
{
ForwardOnCompleted();
}
}
}
internal sealed class ZipObserver<T> : SafeObserver<T>
{
private readonly object _gate;
private readonly IZip _parent;
private readonly int _index;
private readonly Queue<T> _values;
public ZipObserver(object gate, IZip parent, int index)
{
_gate = gate;
_parent = parent;
_index = index;
_values = new Queue<T>();
}
public Queue<T> Values => _values;
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
lock (_gate)
{
_values.Clear();
}
}
}
public override void OnNext(T value)
{
lock (_gate)
{
_values.Enqueue(value);
_parent.Next(_index);
}
}
public override void OnError(Exception error)
{
Dispose();
lock (_gate)
{
_parent.Fail(error);
}
}
public override void OnCompleted()
{
// Calling Dispose() here would clear the queue prematurely.
// We only need to dispose the IDisposable of the upstream,
// which is done by SafeObserver.Dispose(bool).
base.Dispose(true);
lock (_gate)
{
_parent.Done(_index);
}
}
}
#endregion
#endregion
#region N-ary
internal sealed class Zip<TSource> : Producer<IList<TSource>, Zip<TSource>._>
{
private readonly IEnumerable<IObservable<TSource>> _sources;
public Zip(IEnumerable<IObservable<TSource>> sources)
{
_sources = sources;
}
protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
protected override void Run(_ sink) => sink.Run(_sources);
internal sealed class _ : IdentitySink<IList<TSource>>
{
private readonly object _gate;
public _(IObserver<IList<TSource>> observer)
: base(observer)
{
_gate = new object();
}
private Queue<TSource>[] _queues;
private bool[] _isDone;
private IDisposable[] _subscriptions;
public void Run(IEnumerable<IObservable<TSource>> sources)
{
var srcs = sources.ToArray();
var N = srcs.Length;
_queues = new Queue<TSource>[N];
for (var i = 0; i < N; i++)
{
_queues[i] = new Queue<TSource>();
}
_isDone = new bool[N];
var subscriptions = new IDisposable[N];
if (Interlocked.CompareExchange(ref _subscriptions, subscriptions, null) == null)
{
for (var i = 0; i < N; i++)
{
var o = new SourceObserver(this, i);
Disposable.SetSingle(ref subscriptions[i], srcs[i].SubscribeSafe(o));
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var subscriptions = Interlocked.Exchange(ref _subscriptions, Array.Empty<IDisposable>());
if (subscriptions != null && subscriptions != Array.Empty<IDisposable>())
{
for (var i = 0; i < subscriptions.Length; i++)
{
Disposable.TryDispose(ref subscriptions[i]);
}
lock (_gate)
{
foreach (var q in _queues)
{
q.Clear();
}
}
}
}
base.Dispose(disposing);
}
private void OnNext(int index, TSource value)
{
lock (_gate)
{
_queues[index].Enqueue(value);
if (_queues.All(q => q.Count > 0))
{
var n = _queues.Length;
var res = new List<TSource>(n);
for (var i = 0; i < n; i++)
{
res.Add(_queues[i].Dequeue());
}
ForwardOnNext(res);
}
else if (_isDone.AllExcept(index))
{
ForwardOnCompleted();
}
}
}
private new void OnError(Exception error)
{
lock (_gate)
{
ForwardOnError(error);
}
}
private void OnCompleted(int index)
{
lock (_gate)
{
_isDone[index] = true;
if (_isDone.All())
{
ForwardOnCompleted();
}
else
{
var subscriptions = Volatile.Read(ref _subscriptions);
if (subscriptions != null && subscriptions != Array.Empty<IDisposable>())
{
Disposable.TryDispose(ref subscriptions[index]);
}
}
}
}
private sealed class SourceObserver : IObserver<TSource>
{
private readonly _ _parent;
private readonly int _index;
public SourceObserver(_ parent, int index)
{
_parent = parent;
_index = index;
}
public void OnNext(TSource value)
{
_parent.OnNext(_index, value);
}
public void OnError(Exception error)
{
_parent.OnError(error);
}
public void OnCompleted()
{
_parent.OnCompleted(_index);
}
}
}
}
#endregion
}