Concat.cs 10 KB

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