Concat.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<TSource> Concat<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  13. {
  14. if (first == null)
  15. throw Error.ArgumentNull(nameof(first));
  16. if (second == null)
  17. throw Error.ArgumentNull(nameof(second));
  18. return first is ConcatAsyncIterator<TSource> concatFirst ?
  19. concatFirst.Concat(second) :
  20. new Concat2AsyncIterator<TSource>(first, second);
  21. }
  22. private sealed class Concat2AsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  23. {
  24. private readonly IAsyncEnumerable<TSource> _first;
  25. private readonly IAsyncEnumerable<TSource> _second;
  26. internal Concat2AsyncIterator(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  27. {
  28. _first = first;
  29. _second = second;
  30. }
  31. public override AsyncIteratorBase<TSource> Clone()
  32. {
  33. return new Concat2AsyncIterator<TSource>(_first, _second);
  34. }
  35. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  36. {
  37. return new ConcatNAsyncIterator<TSource>(this, next, 2);
  38. }
  39. internal override IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index)
  40. {
  41. switch (index)
  42. {
  43. case 0:
  44. return _first;
  45. case 1:
  46. return _second;
  47. default:
  48. return null;
  49. }
  50. }
  51. }
  52. private abstract class ConcatAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  53. {
  54. private int _counter;
  55. private IAsyncEnumerator<TSource>? _enumerator;
  56. public ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  57. {
  58. return AsyncEnumerableHelpers.ToArray(this, cancellationToken);
  59. }
  60. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  61. {
  62. cancellationToken.ThrowIfCancellationRequested();
  63. var list = new List<TSource>();
  64. for (var i = 0; ; i++)
  65. {
  66. var source = GetAsyncEnumerable(i);
  67. if (source == null)
  68. {
  69. break;
  70. }
  71. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  72. {
  73. list.Add(item);
  74. }
  75. }
  76. return list;
  77. }
  78. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  79. {
  80. if (onlyIfCheap)
  81. {
  82. return new ValueTask<int>(-1);
  83. }
  84. return Core();
  85. async ValueTask<int> Core()
  86. {
  87. cancellationToken.ThrowIfCancellationRequested();
  88. var count = 0;
  89. for (var i = 0; ; i++)
  90. {
  91. var source = GetAsyncEnumerable(i);
  92. if (source == null)
  93. {
  94. break;
  95. }
  96. checked
  97. {
  98. count += await source.CountAsync(cancellationToken).ConfigureAwait(false);
  99. }
  100. }
  101. return count;
  102. }
  103. }
  104. public override async ValueTask DisposeAsync()
  105. {
  106. if (_enumerator != null)
  107. {
  108. await _enumerator.DisposeAsync().ConfigureAwait(false);
  109. _enumerator = null;
  110. }
  111. await base.DisposeAsync().ConfigureAwait(false);
  112. }
  113. protected override async ValueTask<bool> MoveNextCore()
  114. {
  115. if (_state == AsyncIteratorState.Allocated)
  116. {
  117. _enumerator = GetAsyncEnumerable(0)!.GetAsyncEnumerator(_cancellationToken);
  118. _state = AsyncIteratorState.Iterating;
  119. _counter = 2;
  120. }
  121. if (_state == AsyncIteratorState.Iterating)
  122. {
  123. while (true)
  124. {
  125. if (await _enumerator!.MoveNextAsync().ConfigureAwait(false))
  126. {
  127. _current = _enumerator.Current;
  128. return true;
  129. }
  130. //
  131. // NB: This is simply to match the logic of
  132. // https://github.com/dotnet/corefx/blob/f7539b726c4bc2385b7f49e5751c1cff2f2c7368/src/System.Linq/src/System/Linq/Concat.cs#L240
  133. //
  134. var next = GetAsyncEnumerable(_counter++ - 1);
  135. if (next != null)
  136. {
  137. await _enumerator.DisposeAsync().ConfigureAwait(false);
  138. _enumerator = next.GetAsyncEnumerator(_cancellationToken);
  139. continue;
  140. }
  141. await DisposeAsync().ConfigureAwait(false);
  142. break;
  143. }
  144. }
  145. return false;
  146. }
  147. internal abstract ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next);
  148. internal abstract IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index);
  149. }
  150. // To handle chains of >= 3 sources, we chain the concat iterators together and allow
  151. // GetEnumerable to fetch enumerables from the previous sources. This means that rather
  152. // than each MoveNext/Current calls having to traverse all of the previous sources, we
  153. // only have to traverse all of the previous sources once per chained enumerable. An
  154. // alternative would be to use an array to store all of the enumerables, but this has
  155. // a much better memory profile and without much additional run-time cost.
  156. private sealed class ConcatNAsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  157. {
  158. private readonly IAsyncEnumerable<TSource> _next;
  159. private readonly int _nextIndex;
  160. private readonly ConcatAsyncIterator<TSource> _previousConcat;
  161. internal ConcatNAsyncIterator(ConcatAsyncIterator<TSource> previousConcat, IAsyncEnumerable<TSource> next, int nextIndex)
  162. {
  163. Debug.Assert(nextIndex >= 2);
  164. _previousConcat = previousConcat;
  165. _next = next;
  166. _nextIndex = nextIndex;
  167. }
  168. public override AsyncIteratorBase<TSource> Clone()
  169. {
  170. return new ConcatNAsyncIterator<TSource>(_previousConcat, _next, _nextIndex);
  171. }
  172. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  173. {
  174. if (_nextIndex == int.MaxValue - 2)
  175. {
  176. // In the unlikely case of this many concatenations, if we produced a ConcatNIterator
  177. // with int.MaxValue then state would overflow before it matched it's index.
  178. // So we use the naïve approach of just having a left and right sequence.
  179. return new Concat2AsyncIterator<TSource>(this, next);
  180. }
  181. return new ConcatNAsyncIterator<TSource>(this, next, _nextIndex + 1);
  182. }
  183. internal override IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index)
  184. {
  185. if (index > _nextIndex)
  186. {
  187. return null;
  188. }
  189. // Walk back through the chain of ConcatNIterators looking for the one
  190. // that has its _nextIndex equal to index. If we don't find one, then it
  191. // must be prior to any of them, so call GetEnumerable on the previous
  192. // Concat2Iterator. This avoids a deep recursive call chain.
  193. var current = this;
  194. while (true)
  195. {
  196. if (index == current._nextIndex)
  197. {
  198. return current._next;
  199. }
  200. if (current._previousConcat is ConcatNAsyncIterator<TSource> prevN)
  201. {
  202. current = prevN;
  203. continue;
  204. }
  205. Debug.Assert(current._previousConcat is Concat2AsyncIterator<TSource>);
  206. Debug.Assert(index == 0 || index == 1);
  207. return current._previousConcat.GetAsyncEnumerable(index);
  208. }
  209. }
  210. }
  211. }
  212. }