Debian Codegraph @

external/rx/Ix/NET/System.Interactive/EnumerableEx.Buffering.cs

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2 using System;
3 using System.Collections.Generic;
4 using System.Diagnostics;
5
6 namespace System.Linq
7 {
8 public static partial class EnumerableEx
9 {
10 /// <summary>
11 /// Creates a buffer with a shared view over the source sequence, causing each enumerator to fetch the next element from the source sequence.
12 /// </summary>
13 /// <typeparam name="TSource">Source sequence element type.</typeparam>
14 /// <param name="source">Source sequence.</param>
15 /// <returns>Buffer enabling each enumerator to retrieve elements from the shared source sequence.</returns>
16 /// <example>
17 /// var rng = Enumerable.Range(0, 10).Share();
18 ///
19 /// var e1 = rng.GetEnumerator(); // Both e1 and e2 will consume elements from
20 /// var e2 = rng.GetEnumerator(); // the source sequence.
21 ///
22 /// Assert.IsTrue(e1.MoveNext());
23 /// Assert.AreEqual(0, e1.Current);
24 ///
25 /// Assert.IsTrue(e1.MoveNext());
26 /// Assert.AreEqual(1, e1.Current);
27 ///
28 /// Assert.IsTrue(e2.MoveNext()); // e2 "steals" element 2
29 /// Assert.AreEqual(2, e2.Current);
30 ///
31 /// Assert.IsTrue(e1.MoveNext()); // e1 can't see element 2
32 /// Assert.AreEqual(3, e1.Current);
33 /// </example>
34 public static IBuffer<TSource> Share<TSource>(this IEnumerable<TSource> source)
35 {
36 if (source == null)
37 throw new ArgumentNullException("source");
38
39 return new SharedBuffer<TSource>(source.GetEnumerator());
40 }
41
42 /// <summary>
43 /// Shares the source sequence within a selector function where each enumerator can fetch the next element from the source sequence.
44 /// </summary>
45 /// <typeparam name="TSource">Source sequence element type.</typeparam>
46 /// <typeparam name="TResult">Result sequence element type.</typeparam>
47 /// <param name="source">Source sequence.</param>
48 /// <param name="selector">Selector function with shared access to the source sequence for each enumerator.</param>
49 /// <returns>Sequence resulting from applying the selector function to the shared view over the source sequence.</returns>
50 public static IEnumerable<TResult> Share<TSource, TResult>(this IEnumerable<TSource> source, Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
51 {
52 if (source == null)
53 throw new ArgumentNullException("source");
54 if (selector == null)
55 throw new ArgumentNullException("selector");
56
57 return Create<TResult>(() => selector(source.Share()).GetEnumerator());
58 }
59
60 class SharedBuffer<T> : IBuffer<T>
61 {
62 private IEnumerator<T> _source;
63 private bool _disposed;
64
65 public SharedBuffer(IEnumerator<T> source)
66 {
67 _source = source;
68 }
69
70 public IEnumerator<T> GetEnumerator()
71 {
72 if (_disposed)
73 throw new ObjectDisposedException("");
74
75 return GetEnumerator_();
76 }
77
78 private IEnumerator<T> GetEnumerator_()
79 {
80 while (true)
81 {
82 if (_disposed)
83 throw new ObjectDisposedException("");
84
85 var hasValue = default(bool);
86 var current = default(T);
87
88 lock (_source)
89 {
90 hasValue = _source.MoveNext();
91 if (hasValue)
92 current = _source.Current;
93 }
94
95 if (hasValue)
96 yield return current;
97 else
98 break;
99 }
100 }
101
102 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
103 {
104 if (_disposed)
105 throw new ObjectDisposedException("");
106
107 return GetEnumerator();
108 }
109
110 public void Dispose()
111 {
112 lock (_source)
113 {
114 if (!_disposed)
115 {
116 _source.Dispose();
117 _source = null;
118 }
119
120 _disposed = true;
121 }
122 }
123 }
124
125 /// <summary>
126 /// 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.
127 /// </summary>
128 /// <typeparam name="TSource">Source sequence element type.</typeparam>
129 /// <param name="source">Source sequence.</param>
130 /// <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>
131 /// <example>
132 /// var rng = Enumerable.Range(0, 10).Publish();
133 ///
134 /// var e1 = rng.GetEnumerator(); // e1 has a view on the source starting from element 0
135 ///
136 /// Assert.IsTrue(e1.MoveNext());
137 /// Assert.AreEqual(0, e1.Current);
138 ///
139 /// Assert.IsTrue(e1.MoveNext());
140 /// Assert.AreEqual(1, e1.Current);
141 ///
142 /// var e2 = rng.GetEnumerator();
143 ///
144 /// Assert.IsTrue(e2.MoveNext()); // e2 has a view on the source starting from element 2
145 /// Assert.AreEqual(2, e2.Current);
146 ///
147 /// Assert.IsTrue(e1.MoveNext()); // e1 continues to enumerate over its view
148 /// Assert.AreEqual(2, e1.Current);
149 /// </example>
150 public static IBuffer<TSource> Publish<TSource>(this IEnumerable<TSource> source)
151 {
152 if (source == null)
153 throw new ArgumentNullException("source");
154
155 return new PublishedBuffer<TSource>(source.GetEnumerator());
156 }
157
158 /// <summary>
159 /// Publishes the source sequence within a selector function where each enumerator can obtain a view over a tail of the source sequence.
160 /// </summary>
161 /// <typeparam name="TSource">Source sequence element type.</typeparam>
162 /// <typeparam name="TResult">Result sequence element type.</typeparam>
163 /// <param name="source">Source sequence.</param>
164 /// <param name="selector">Selector function with published access to the source sequence for each enumerator.</param>
165 /// <returns>Sequence resulting from applying the selector function to the published view over the source sequence.</returns>
166 public static IEnumerable<TResult> Publish<TSource, TResult>(this IEnumerable<TSource> source, Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
167 {
168 if (source == null)
169 throw new ArgumentNullException("source");
170 if (selector == null)
171 throw new ArgumentNullException("selector");
172
173 return Create<TResult>(() => selector(source.Publish()).GetEnumerator());
174 }
175
176 class PublishedBuffer<T> : IBuffer<T>
177 {
178 private IEnumerator<T> _source;
179 private RefCountList<T> _buffer;
180 private bool _stopped;
181 private Exception _error;
182 private bool _disposed;
183
184 public PublishedBuffer(IEnumerator<T> source)
185 {
186 _buffer = new RefCountList<T>(0);
187 _source = source;
188 }
189
190 public IEnumerator<T> GetEnumerator()
191 {
192 if (_disposed)
193 throw new ObjectDisposedException("");
194
195 var i = default(int);
196 lock (_source)
197 {
198 i = _buffer.Count;
199 _buffer.ReaderCount++;
200 }
201
202 return GetEnumerator_(i);
203 }
204
205 private IEnumerator<T> GetEnumerator_(int i)
206 {
207 try
208 {
209 while (true)
210 {
211 if (_disposed)
212 throw new ObjectDisposedException("");
213
214 var hasValue = default(bool);
215 var current = default(T);
216
217 lock (_source)
218 {
219 if (i >= _buffer.Count)
220 {
221 if (!_stopped)
222 {
223 try
224 {
225 hasValue = _source.MoveNext();
226 if (hasValue)
227 current = _source.Current;
228 }
229 catch (Exception ex)
230 {
231 _stopped = true;
232 _error = ex;
233
234 _source.Dispose();
235 }
236 }
237
238 if (_stopped)
239 {
240 if (_error != null)
241 throw _error;
242 else
243 break;
244 }
245
246 if (hasValue)
247 {
248 _buffer.Add(current);
249 }
250 }
251 else
252 {
253 hasValue = true;
254 }
255 }
256
257 if (hasValue)
258 yield return _buffer[i];
259 else
260 break;
261
262 i++;
263 }
264 }
265 finally
266 {
267 if (_buffer != null)
268 _buffer.Done(i + 1);
269 }
270 }
271
272 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
273 {
274 if (_disposed)
275 throw new ObjectDisposedException("");
276
277 return GetEnumerator();
278 }
279
280 public void Dispose()
281 {
282 lock (_source)
283 {
284 if (!_disposed)
285 {
286 _source.Dispose();
287 _source = null;
288
289 _buffer.Clear();
290 _buffer = null;
291 }
292
293 _disposed = true;
294 }
295 }
296 }
297
298 /// <summary>
299 /// Creates a buffer with a view over the source sequence, causing each enumerator to obtain access to all of the sequence's elements without causing multiple enumerations over the source.
300 /// </summary>
301 /// <typeparam name="TSource">Source sequence element type.</typeparam>
302 /// <param name="source">Source sequence.</param>
303 /// <returns>Buffer enabling each enumerator to retrieve all elements from the shared source sequence, without duplicating source enumeration side-effects.</returns>
304 /// <example>
305 /// var rng = Enumerable.Range(0, 10).Do(x => Console.WriteLine(x)).Memoize();
306 ///
307 /// var e1 = rng.GetEnumerator();
308 ///
309 /// Assert.IsTrue(e1.MoveNext()); // Prints 0
310 /// Assert.AreEqual(0, e1.Current);
311 ///
312 /// Assert.IsTrue(e1.MoveNext()); // Prints 1
313 /// Assert.AreEqual(1, e1.Current);
314 ///
315 /// var e2 = rng.GetEnumerator();
316 ///
317 /// Assert.IsTrue(e2.MoveNext()); // Doesn't print anything; the side-effect of Do
318 /// Assert.AreEqual(0, e2.Current); // has already taken place during e1's iteration.
319 ///
320 /// Assert.IsTrue(e1.MoveNext()); // Prints 2
321 /// Assert.AreEqual(2, e1.Current);
322 /// </example>
323 public static IBuffer<TSource> Memoize<TSource>(this IEnumerable<TSource> source)
324 {
325 if (source == null)
326 throw new ArgumentNullException("source");
327
328 return new MemoizedBuffer<TSource>(source.GetEnumerator());
329 }
330
331 /// <summary>
332 /// Memoizes the source sequence within a selector function where each enumerator can get access to all of the sequence's elements without causing multiple enumerations over the source.
333 /// </summary>
334 /// <typeparam name="TSource">Source sequence element type.</typeparam>
335 /// <typeparam name="TResult">Result sequence element type.</typeparam>
336 /// <param name="source">Source sequence.</param>
337 /// <param name="selector">Selector function with memoized access to the source sequence for each enumerator.</param>
338 /// <returns>Sequence resulting from applying the selector function to the memoized view over the source sequence.</returns>
339 public static IEnumerable<TResult> Memoize<TSource, TResult>(this IEnumerable<TSource> source, Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
340 {
341 if (source == null)
342 throw new ArgumentNullException("source");
343 if (selector == null)
344 throw new ArgumentNullException("selector");
345
346 return Create<TResult>(() => selector(source.Memoize()).GetEnumerator());
347 }
348
349 /// <summary>
350 /// Creates a buffer with a view over the source sequence, causing a specified number of enumerators to obtain access to all of the sequence's elements without causing multiple enumerations over the source.
351 /// </summary>
352 /// <typeparam name="TSource">Source sequence element type.</typeparam>
353 /// <param name="source">Source sequence.</param>
354 /// <param name="readerCount">Number of enumerators that can access the underlying buffer. Once every enumerator has obtained an element from the buffer, the element is removed from the buffer.</param>
355 /// <returns>Buffer enabling a specified number of enumerators to retrieve all elements from the shared source sequence, without duplicating source enumeration side-effects.</returns>
356 public static IBuffer<TSource> Memoize<TSource>(this IEnumerable<TSource> source, int readerCount)
357 {
358 if (source == null)
359 throw new ArgumentNullException("source");
360 if (readerCount <= 0)
361 throw new ArgumentOutOfRangeException("readerCount");
362
363 return new MemoizedBuffer<TSource>(source.GetEnumerator(), readerCount);
364 }
365
366 /// <summary>
367 /// Memoizes the source sequence within a selector function where a specified number of enumerators can get access to all of the sequence's elements without causing multiple enumerations over the source.
368 /// </summary>
369 /// <typeparam name="TSource">Source sequence element type.</typeparam>
370 /// <typeparam name="TResult">Result sequence element type.</typeparam>
371 /// <param name="source">Source sequence.</param>
372 /// <param name="readerCount">Number of enumerators that can access the underlying buffer. Once every enumerator has obtained an element from the buffer, the element is removed from the buffer.</param>
373 /// <param name="selector">Selector function with memoized access to the source sequence for a specified number of enumerators.</param>
374 /// <returns>Sequence resulting from applying the selector function to the memoized view over the source sequence.</returns>
375 public static IEnumerable<TResult> Memoize<TSource, TResult>(this IEnumerable<TSource> source, int readerCount, Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
376 {
377 if (source == null)
378 throw new ArgumentNullException("source");
379 if (readerCount <= 0)
380 throw new ArgumentOutOfRangeException("readerCount");
381 if (selector == null)
382 throw new ArgumentNullException("selector");
383
384 return Create<TResult>(() => selector(source.Memoize(readerCount)).GetEnumerator());
385 }
386
387 class MemoizedBuffer<T> : IBuffer<T>
388 {
389 private IEnumerator<T> _source;
390 private IRefCountList<T> _buffer;
391 private bool _stopped;
392 private Exception _error;
393 private bool _disposed;
394
395 public MemoizedBuffer(IEnumerator<T> source)
396 : this(source, new MaxRefCountList<T>())
397 {
398 }
399
400 public MemoizedBuffer(IEnumerator<T> source, int readerCount)
401 : this(source, new RefCountList<T>(readerCount))
402 {
403 }
404
405 private MemoizedBuffer(IEnumerator<T> source, IRefCountList<T> buffer)
406 {
407 _source = source;
408 _buffer = buffer;
409 }
410
411 public IEnumerator<T> GetEnumerator()
412 {
413 if (_disposed)
414 throw new ObjectDisposedException("");
415
416 return GetEnumerator_();
417 }
418
419 private IEnumerator<T> GetEnumerator_()
420 {
421 var i = 0;
422
423 try
424 {
425 while (true)
426 {
427 if (_disposed)
428 throw new ObjectDisposedException("");
429
430 var hasValue = default(bool);
431 var current = default(T);
432
433 lock (_source)
434 {
435 if (i >= _buffer.Count)
436 {
437 if (!_stopped)
438 {
439 try
440 {
441 hasValue = _source.MoveNext();
442 if (hasValue)
443 current = _source.Current;
444 }
445 catch (Exception ex)
446 {
447 _stopped = true;
448 _error = ex;
449
450 _source.Dispose();
451 }
452 }
453
454 if (_stopped)
455 {
456 if (_error != null)
457 throw _error;
458 else
459 break;
460 }
461
462 if (hasValue)
463 {
464 _buffer.Add(current);
465 }
466 }
467 else
468 {
469 hasValue = true;
470 }
471 }
472
473 if (hasValue)
474 yield return _buffer[i];
475 else
476 break;
477
478 i++;
479 }
480 }
481 finally
482 {
483 if (_buffer != null)
484 _buffer.Done(i + 1);
485 }
486 }
487
488 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
489 {
490 if (_disposed)
491 throw new ObjectDisposedException("");
492
493 return GetEnumerator();
494 }
495
496 public void Dispose()
497 {
498 lock (_source)
499 {
500 if (!_disposed)
501 {
502 _source.Dispose();
503 _source = null;
504
505 _buffer.Clear();
506 _buffer = null;
507 }
508
509 _disposed = true;
510 }
511 }
512 }
513 }
514
515 /// <summary>
516 /// Represents a buffer exposing a shared view over an underlying enumerable sequence.
517 /// </summary>
518 /// <typeparam name="T">Element type.</typeparam>
519 public interface IBuffer<
520 #if !NO_VARIANCE && !SILVERLIGHT4 // SL4 has defined IEnumerable with invariant T
521 out
522 #endif
523 T> : IEnumerable<T>, IDisposable
524 {
525 }
526
527 interface IRefCountList<T>
528 {
529 void Clear();
530
531 int Count { get; }
532
533 T this[int i]
534 {
535 get;
536 }
537
538 void Add(T item);
539
540 void Done(int index);
541 }
542
543 class MaxRefCountList<T> : IRefCountList<T>
544 {
545 private IList<T> _list = new List<T>();
546
547 public void Clear()
548 {
549 _list.Clear();
550 }
551
552 public int Count
553 {
554 get { return _list.Count; }
555 }
556
557 public T this[int i]
558 {
559 get { return _list[i]; }
560 }
561
562 public void Add(T item)
563 {
564 _list.Add(item);
565 }
566
567 public void Done(int index)
568 {
569 }
570 }
571
572 class RefCountList<T> : IRefCountList<T>
573 {
574 private int _readerCount;
575 private readonly IDictionary<int, RefCount> _list;
576 private int _count;
577
578 public RefCountList(int readerCount)
579 {
580 _readerCount = readerCount;
581 _list = new Dictionary<int, RefCount>();
582 }
583
584 public int ReaderCount
585 {
586 get
587 {
588 return _readerCount;
589 }
590
591 set
592 {
593 _readerCount = value;
594 }
595 }
596
597 public void Clear()
598 {
599 _list.Clear();
600 }
601
602 public int Count
603 {
604 get { return _count; }
605 }
606
607 public T this[int i]
608 {
609 get
610 {
611 Debug.Assert(i < _count);
612
613 var res = default(RefCount);
614 if (!_list.TryGetValue(i, out res))
615 throw new InvalidOperationException("Element no longer available in the buffer.");
616
617 var val = res.Value;
618 if (--res.Count == 0)
619 _list.Remove(i);
620
621 return val;
622 }
623 }
624
625 public void Add(T item)
626 {
627 _list[_count] = new RefCount { Value = item, Count = _readerCount };
628 _count++;
629 }
630
631 public void Done(int index)
632 {
633 for (int i = index; i < _count; i++)
634 {
635 var ignore = this[i];
636 }
637
638 _readerCount--;
639 }
640
641 class RefCount
642 {
643 public int Count;
644 public T Value;
645 }
646 }
647 }