Concat.cs 9.5 KB

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