Scan.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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<TAccumulate> Scan<TSource, TAccumulate>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. if (accumulator == null)
  18. throw new ArgumentNullException(nameof(accumulator));
  19. return Create(() =>
  20. {
  21. var e = source.GetEnumerator();
  22. var cts = new CancellationTokenDisposable();
  23. var d = Disposable.Create(cts, e);
  24. var acc = seed;
  25. var current = default(TAccumulate);
  26. var f = default(Func<CancellationToken, Task<bool>>);
  27. f = async ct =>
  28. {
  29. if (!await e.MoveNext(ct)
  30. .ConfigureAwait(false))
  31. {
  32. return false;
  33. }
  34. var item = e.Current;
  35. acc = accumulator(acc, item);
  36. current = acc;
  37. return true;
  38. };
  39. return Create(
  40. f,
  41. () => current,
  42. d.Dispose,
  43. e
  44. );
  45. });
  46. }
  47. public static IAsyncEnumerable<TSource> Scan<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, TSource, TSource> accumulator)
  48. {
  49. if (source == null)
  50. throw new ArgumentNullException(nameof(source));
  51. if (accumulator == null)
  52. throw new ArgumentNullException(nameof(accumulator));
  53. return Create(() =>
  54. {
  55. var e = source.GetEnumerator();
  56. var cts = new CancellationTokenDisposable();
  57. var d = Disposable.Create(cts, e);
  58. var hasSeed = false;
  59. var acc = default(TSource);
  60. var current = default(TSource);
  61. var f = default(Func<CancellationToken, Task<bool>>);
  62. f = async ct =>
  63. {
  64. if (!await e.MoveNext(ct)
  65. .ConfigureAwait(false))
  66. {
  67. return false;
  68. }
  69. var item = e.Current;
  70. if (!hasSeed)
  71. {
  72. hasSeed = true;
  73. acc = item;
  74. return await f(ct)
  75. .ConfigureAwait(false);
  76. }
  77. acc = accumulator(acc, item);
  78. current = acc;
  79. return true;
  80. };
  81. return Create(
  82. f,
  83. () => current,
  84. d.Dispose,
  85. e
  86. );
  87. });
  88. }
  89. }
  90. }