Scan.cs 3.8 KB

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