Concat.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. var concatFirst = first as ConcatAsyncIterator<TSource>;
  19. return concatFirst != null ?
  20. concatFirst.Concat(second) :
  21. new Concat2AsyncIterator<TSource>(first, second);
  22. }
  23. private sealed class Concat2AsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  24. {
  25. private readonly IAsyncEnumerable<TSource> first;
  26. private readonly IAsyncEnumerable<TSource> second;
  27. internal Concat2AsyncIterator(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  28. {
  29. Debug.Assert(first != null);
  30. Debug.Assert(second != null);
  31. this.first = first;
  32. this.second = second;
  33. }
  34. public override AsyncIterator<TSource> Clone()
  35. {
  36. return new Concat2AsyncIterator<TSource>(first, second);
  37. }
  38. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  39. {
  40. return new ConcatNAsyncIterator<TSource>(this, next, 2);
  41. }
  42. internal override IAsyncEnumerable<TSource> GetAsyncEnumerable(int index)
  43. {
  44. switch (index)
  45. {
  46. case 0:
  47. return first;
  48. case 1:
  49. return second;
  50. default:
  51. return null;
  52. }
  53. }
  54. }
  55. private abstract class ConcatAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  56. {
  57. private int counter;
  58. private IAsyncEnumerator<TSource> enumerator;
  59. public Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  60. {
  61. return AsyncEnumerableHelpers.ToArray(this, cancellationToken);
  62. }
  63. public async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  64. {
  65. var list = new List<TSource>();
  66. for (var i = 0; ; i++)
  67. {
  68. var source = GetAsyncEnumerable(i);
  69. if (source == null)
  70. {
  71. break;
  72. }
  73. var e = source.GetAsyncEnumerator();
  74. try
  75. {
  76. while (await e.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  77. {
  78. list.Add(e.Current);
  79. }
  80. }
  81. finally
  82. {
  83. await e.DisposeAsync().ConfigureAwait(false);
  84. }
  85. }
  86. return list;
  87. }
  88. public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  89. {
  90. if (onlyIfCheap)
  91. {
  92. return -1;
  93. }
  94. var count = 0;
  95. for (var i = 0; ; i++)
  96. {
  97. var source = GetAsyncEnumerable(i);
  98. if (source == null)
  99. {
  100. break;
  101. }
  102. checked
  103. {
  104. count += await source.Count(cancellationToken).ConfigureAwait(false);
  105. }
  106. }
  107. return count;
  108. }
  109. public override async Task 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 Task<bool> MoveNextCore()
  119. {
  120. if (state == AsyncIteratorState.Allocated)
  121. {
  122. enumerator = GetAsyncEnumerable(0).GetAsyncEnumerator();
  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. // note, this is simply to match the logic of
  136. // https://github.com/dotnet/corefx/blob/ec2685715b01d12f16b08d0dfa326649b12db8ec/src/system.linq/src/system/linq/concatenate.cs#L173-L173
  137. var next = GetAsyncEnumerable(counter++ - 1);
  138. if (next != null)
  139. {
  140. await enumerator.DisposeAsync().ConfigureAwait(false);
  141. enumerator = next.GetAsyncEnumerator();
  142. continue;
  143. }
  144. await DisposeAsync().ConfigureAwait(false);
  145. break;
  146. }
  147. }
  148. return false;
  149. }
  150. internal abstract ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next);
  151. internal abstract IAsyncEnumerable<TSource> GetAsyncEnumerable(int index);
  152. }
  153. // To handle chains of >= 3 sources, we chain the concat iterators together and allow
  154. // GetEnumerable to fetch enumerables from the previous sources. This means that rather
  155. // than each MoveNext/Current calls having to traverse all of the previous sources, we
  156. // only have to traverse all of the previous sources once per chained enumerable. An
  157. // alternative would be to use an array to store all of the enumerables, but this has
  158. // a much better memory profile and without much additional run-time cost.
  159. private sealed class ConcatNAsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  160. {
  161. private readonly IAsyncEnumerable<TSource> next;
  162. private readonly int nextIndex;
  163. private readonly ConcatAsyncIterator<TSource> previousConcat;
  164. internal ConcatNAsyncIterator(ConcatAsyncIterator<TSource> previousConcat, IAsyncEnumerable<TSource> next, int nextIndex)
  165. {
  166. Debug.Assert(previousConcat != null);
  167. Debug.Assert(next != null);
  168. Debug.Assert(nextIndex >= 2);
  169. this.previousConcat = previousConcat;
  170. this.next = next;
  171. this.nextIndex = nextIndex;
  172. }
  173. public override AsyncIterator<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. }