Buffer.cs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. if (count <= 0)
  18. throw new ArgumentOutOfRangeException(nameof(count));
  19. return source.Buffer_(count, count);
  20. }
  21. public static IAsyncEnumerable<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count, int skip)
  22. {
  23. if (source == null)
  24. throw new ArgumentNullException(nameof(source));
  25. if (count <= 0)
  26. throw new ArgumentOutOfRangeException(nameof(count));
  27. if (skip <= 0)
  28. throw new ArgumentOutOfRangeException(nameof(skip));
  29. return source.Buffer_(count, skip);
  30. }
  31. private static IAsyncEnumerable<IList<TSource>> Buffer_<TSource>(this IAsyncEnumerable<TSource> source, int count, int skip)
  32. {
  33. return CreateEnumerable(
  34. () =>
  35. {
  36. var e = source.GetEnumerator();
  37. var cts = new CancellationTokenDisposable();
  38. var d = Disposable.Create(cts, e);
  39. var buffers = new Queue<IList<TSource>>();
  40. var i = 0;
  41. var current = default(IList<TSource>);
  42. var stopped = false;
  43. var f = default(Func<CancellationToken, Task<bool>>);
  44. f = async ct =>
  45. {
  46. if (!stopped)
  47. {
  48. if (await e.MoveNext(ct)
  49. .ConfigureAwait(false))
  50. {
  51. var item = e.Current;
  52. if (i++%skip == 0)
  53. buffers.Enqueue(new List<TSource>(count));
  54. foreach (var buffer in buffers)
  55. buffer.Add(item);
  56. if (buffers.Count > 0 && buffers.Peek()
  57. .Count == count)
  58. {
  59. current = buffers.Dequeue();
  60. return true;
  61. }
  62. return await f(ct)
  63. .ConfigureAwait(false);
  64. }
  65. stopped = true;
  66. e.Dispose();
  67. return await f(ct)
  68. .ConfigureAwait(false);
  69. }
  70. if (buffers.Count > 0)
  71. {
  72. current = buffers.Dequeue();
  73. return true;
  74. }
  75. return false;
  76. };
  77. return CreateEnumerator(
  78. f,
  79. () => current,
  80. d.Dispose,
  81. e
  82. );
  83. });
  84. }
  85. }
  86. }