-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Publish.cs
234 lines (194 loc) · 5.27 KB
/
Publish.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
using System.Runtime.ExceptionServices;
namespace SuperLinq.Async;
public static partial class AsyncSuperEnumerable
{
/// <summary>
/// Creates a buffer with a view over the source sequence, causing each enumerator to obtain access to the remainder
/// of the sequence from the current index in the buffer.
/// </summary>
/// <typeparam name="TSource">Source sequence element type.</typeparam>
/// <param name="source">Source sequence.</param>
/// <returns>
/// Buffer enabling each enumerator to retrieve elements from the shared source sequence, starting from the index at
/// the point of obtaining the enumerator.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception>
public static IAsyncBuffer<TSource> Publish<TSource>(this IAsyncEnumerable<TSource> source)
{
ArgumentNullException.ThrowIfNull(source);
return new PublishBuffer<TSource>(source);
}
private sealed class PublishBuffer<T>(
IAsyncEnumerable<T> source
) : IAsyncBuffer<T>
{
private readonly SemaphoreSlim _lock = new(initialCount: 1);
private IAsyncEnumerable<T>? _source = source;
private IAsyncEnumerator<T>? _enumerator;
private List<Queue<T>>? _buffers;
private bool _initialized;
private int _version;
private ExceptionDispatchInfo? _exception;
private bool? _exceptionOnGetEnumerator;
private bool _disposed;
public int Count => _buffers?.Count > 0 ? _buffers.Max(x => x.Count) : 0;
public async ValueTask Reset(CancellationToken cancellationToken = default)
{
if (_disposed)
ThrowHelper.ThrowObjectDisposedException<IAsyncBuffer<T>>();
await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_disposed)
ThrowHelper.ThrowObjectDisposedException<IAsyncBuffer<T>>();
_initialized = false;
_version++;
_buffers = null;
if (_enumerator is not null)
await _enumerator.DisposeAsync();
_enumerator = null;
_exception = null;
_exceptionOnGetEnumerator = null;
}
finally
{
_ = _lock.Release();
}
}
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
var (buffer, version) = InitializeEnumerator(cancellationToken);
return GetEnumeratorImpl(buffer, version, cancellationToken);
}
private (Queue<T> buffer, int version) InitializeEnumerator(CancellationToken cancellationToken)
{
if (_disposed)
ThrowHelper.ThrowObjectDisposedException<IAsyncBuffer<T>>();
_lock.Wait(cancellationToken);
try
{
if (_disposed)
ThrowHelper.ThrowObjectDisposedException<IAsyncBuffer<T>>();
Assert.NotNull(_source);
if (_exceptionOnGetEnumerator == true)
{
Assert.NotNull(_exception);
_exception.Throw();
}
if (!_initialized)
{
try
{
_enumerator = _source.GetAsyncEnumerator(cancellationToken);
_buffers = [];
_initialized = true;
}
catch (Exception ex)
{
_exception = ExceptionDispatchInfo.Capture(ex);
_exceptionOnGetEnumerator = true;
throw;
}
}
Assert.NotNull(_buffers);
var queue = new Queue<T>();
_buffers.Add(queue);
return (queue, _version);
}
finally
{
_ = _lock.Release();
}
}
private async IAsyncEnumerator<T> GetEnumeratorImpl(Queue<T> buffer, int version, CancellationToken cancellationToken)
{
try
{
while (true)
{
T? element;
if (_disposed)
ThrowHelper.ThrowObjectDisposedException<IAsyncBuffer<T>>();
await _lock.WaitAsync(cancellationToken);
try
{
if (_disposed)
ThrowHelper.ThrowObjectDisposedException<IBuffer<T>>();
if (!_initialized
|| version != _version)
{
ThrowHelper.ThrowInvalidOperationException("Buffer reset during iteration.");
}
if (buffer.Count == 0)
{
_exception?.Throw();
if (_enumerator is null)
break;
var moved = false;
try
{
moved = await _enumerator.MoveNextAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_exception = ExceptionDispatchInfo.Capture(ex);
_exceptionOnGetEnumerator = false;
await _enumerator.DisposeAsync().ConfigureAwait(false);
_enumerator = null;
throw;
}
if (!moved)
{
await _enumerator.DisposeAsync().ConfigureAwait(false);
_enumerator = null;
break;
}
Assert.NotNull(_buffers);
var current = _enumerator.Current;
foreach (var q in _buffers)
q.Enqueue(current);
}
element = buffer.Dequeue();
}
finally
{
_ = _lock.Release();
}
yield return element;
}
}
finally
{
await _lock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
_ = _buffers?.Remove(buffer);
}
finally
{
_ = _lock.Release();
}
}
}
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
await _lock.WaitAsync().ConfigureAwait(false);
try
{
_disposed = true;
_buffers = null;
if (_enumerator is not null)
await _enumerator.DisposeAsync().ConfigureAwait(false);
_enumerator = null;
_source = null;
}
finally
{
_ = _lock.Release();
_lock.Dispose();
}
}
}
}