Concat.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. public static IAsyncEnumerable<TSource> Concat<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  24. {
  25. if (sources == null)
  26. throw new ArgumentNullException(nameof(sources));
  27. return sources.Concat_();
  28. }
  29. public static IAsyncEnumerable<TSource> Concat<TSource>(params IAsyncEnumerable<TSource>[] sources)
  30. {
  31. if (sources == null)
  32. throw new ArgumentNullException(nameof(sources));
  33. return sources.Concat_();
  34. }
  35. private static IAsyncEnumerable<TSource> Concat_<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  36. {
  37. return new ConcatEnumerableAsyncIterator<TSource>(sources);
  38. }
  39. private sealed class ConcatEnumerableAsyncIterator<TSource> : AsyncIterator<TSource>
  40. {
  41. private readonly IEnumerable<IAsyncEnumerable<TSource>> source;
  42. public ConcatEnumerableAsyncIterator(IEnumerable<IAsyncEnumerable<TSource>> source)
  43. {
  44. Debug.Assert(source != null);
  45. this.source = source;
  46. }
  47. public override AsyncIterator<TSource> Clone()
  48. {
  49. return new ConcatEnumerableAsyncIterator<TSource>(source);
  50. }
  51. public override async Task DisposeAsync()
  52. {
  53. if (outerEnumerator != null)
  54. {
  55. outerEnumerator.Dispose();
  56. outerEnumerator = null;
  57. }
  58. if (currentEnumerator != null)
  59. {
  60. await currentEnumerator.DisposeAsync().ConfigureAwait(false);
  61. currentEnumerator = null;
  62. }
  63. await base.DisposeAsync().ConfigureAwait(false);
  64. }
  65. // State machine vars
  66. private IEnumerator<IAsyncEnumerable<TSource>> outerEnumerator;
  67. private IAsyncEnumerator<TSource> currentEnumerator;
  68. private int mode;
  69. private const int State_OuterNext = 1;
  70. private const int State_While = 4;
  71. protected override async Task<bool> MoveNextCore()
  72. {
  73. switch (state)
  74. {
  75. case AsyncIteratorState.Allocated:
  76. outerEnumerator = source.GetEnumerator();
  77. mode = State_OuterNext;
  78. state = AsyncIteratorState.Iterating;
  79. goto case AsyncIteratorState.Iterating;
  80. case AsyncIteratorState.Iterating:
  81. switch (mode)
  82. {
  83. case State_OuterNext:
  84. if (outerEnumerator.MoveNext())
  85. {
  86. // make sure we dispose the previous one if we're about to replace it
  87. if (currentEnumerator != null)
  88. {
  89. await currentEnumerator.DisposeAsync().ConfigureAwait(false);
  90. }
  91. currentEnumerator = outerEnumerator.Current.GetAsyncEnumerator();
  92. mode = State_While;
  93. goto case State_While;
  94. }
  95. break;
  96. case State_While:
  97. if (await currentEnumerator.MoveNextAsync().ConfigureAwait(false))
  98. {
  99. current = currentEnumerator.Current;
  100. return true;
  101. }
  102. // No more on the inner enumerator, move to the next outer
  103. goto case State_OuterNext;
  104. }
  105. await DisposeAsync().ConfigureAwait(false);
  106. break;
  107. }
  108. return false;
  109. }
  110. }
  111. private sealed class Concat2AsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  112. {
  113. private readonly IAsyncEnumerable<TSource> first;
  114. private readonly IAsyncEnumerable<TSource> second;
  115. internal Concat2AsyncIterator(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  116. {
  117. Debug.Assert(first != null);
  118. Debug.Assert(second != null);
  119. this.first = first;
  120. this.second = second;
  121. }
  122. public override AsyncIterator<TSource> Clone()
  123. {
  124. return new Concat2AsyncIterator<TSource>(first, second);
  125. }
  126. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  127. {
  128. return new ConcatNAsyncIterator<TSource>(this, next, 2);
  129. }
  130. internal override IAsyncEnumerable<TSource> GetAsyncEnumerable(int index)
  131. {
  132. switch (index)
  133. {
  134. case 0:
  135. return first;
  136. case 1:
  137. return second;
  138. default:
  139. return null;
  140. }
  141. }
  142. }
  143. private abstract class ConcatAsyncIterator<TSource> : AsyncIterator<TSource>, IIListProvider<TSource>
  144. {
  145. private int counter;
  146. private IAsyncEnumerator<TSource> enumerator;
  147. public Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  148. {
  149. return AsyncEnumerableHelpers.ToArray(this, cancellationToken);
  150. }
  151. public async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  152. {
  153. var list = new List<TSource>();
  154. for (var i = 0;; i++)
  155. {
  156. var source = GetAsyncEnumerable(i);
  157. if (source == null)
  158. {
  159. break;
  160. }
  161. var e = source.GetAsyncEnumerator();
  162. try
  163. {
  164. while (await e.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  165. {
  166. list.Add(e.Current);
  167. }
  168. }
  169. finally
  170. {
  171. await e.DisposeAsync().ConfigureAwait(false);
  172. }
  173. }
  174. return list;
  175. }
  176. public async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  177. {
  178. if (onlyIfCheap)
  179. {
  180. return -1;
  181. }
  182. var count = 0;
  183. for (var i = 0;; i++)
  184. {
  185. var source = GetAsyncEnumerable(i);
  186. if (source == null)
  187. {
  188. break;
  189. }
  190. checked
  191. {
  192. count += await source.Count(cancellationToken).ConfigureAwait(false);
  193. }
  194. }
  195. return count;
  196. }
  197. public override async Task DisposeAsync()
  198. {
  199. if (enumerator != null)
  200. {
  201. await enumerator.DisposeAsync().ConfigureAwait(false);
  202. enumerator = null;
  203. }
  204. await base.DisposeAsync().ConfigureAwait(false);
  205. }
  206. protected override async Task<bool> MoveNextCore()
  207. {
  208. if (state == AsyncIteratorState.Allocated)
  209. {
  210. enumerator = GetAsyncEnumerable(0).GetAsyncEnumerator();
  211. state = AsyncIteratorState.Iterating;
  212. counter = 2;
  213. }
  214. if (state == AsyncIteratorState.Iterating)
  215. {
  216. while (true)
  217. {
  218. if (await enumerator.MoveNextAsync().ConfigureAwait(false))
  219. {
  220. current = enumerator.Current;
  221. return true;
  222. }
  223. // note, this is simply to match the logic of
  224. // https://github.com/dotnet/corefx/blob/ec2685715b01d12f16b08d0dfa326649b12db8ec/src/system.linq/src/system/linq/concatenate.cs#L173-L173
  225. var next = GetAsyncEnumerable(counter++ - 1);
  226. if (next != null)
  227. {
  228. await enumerator.DisposeAsync().ConfigureAwait(false);
  229. enumerator = next.GetAsyncEnumerator();
  230. continue;
  231. }
  232. await DisposeAsync().ConfigureAwait(false);
  233. break;
  234. }
  235. }
  236. return false;
  237. }
  238. internal abstract ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next);
  239. internal abstract IAsyncEnumerable<TSource> GetAsyncEnumerable(int index);
  240. }
  241. // To handle chains of >= 3 sources, we chain the concat iterators together and allow
  242. // GetEnumerable to fetch enumerables from the previous sources. This means that rather
  243. // than each MoveNext/Current calls having to traverse all of the previous sources, we
  244. // only have to traverse all of the previous sources once per chained enumerable. An
  245. // alternative would be to use an array to store all of the enumerables, but this has
  246. // a much better memory profile and without much additional run-time cost.
  247. private sealed class ConcatNAsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  248. {
  249. private readonly IAsyncEnumerable<TSource> next;
  250. private readonly int nextIndex;
  251. private readonly ConcatAsyncIterator<TSource> previousConcat;
  252. internal ConcatNAsyncIterator(ConcatAsyncIterator<TSource> previousConcat, IAsyncEnumerable<TSource> next, int nextIndex)
  253. {
  254. Debug.Assert(previousConcat != null);
  255. Debug.Assert(next != null);
  256. Debug.Assert(nextIndex >= 2);
  257. this.previousConcat = previousConcat;
  258. this.next = next;
  259. this.nextIndex = nextIndex;
  260. }
  261. public override AsyncIterator<TSource> Clone()
  262. {
  263. return new ConcatNAsyncIterator<TSource>(previousConcat, next, nextIndex);
  264. }
  265. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  266. {
  267. if (nextIndex == int.MaxValue - 2)
  268. {
  269. // In the unlikely case of this many concatenations, if we produced a ConcatNIterator
  270. // with int.MaxValue then state would overflow before it matched it's index.
  271. // So we use the naïve approach of just having a left and right sequence.
  272. return new Concat2AsyncIterator<TSource>(this, next);
  273. }
  274. return new ConcatNAsyncIterator<TSource>(this, next, nextIndex + 1);
  275. }
  276. internal override IAsyncEnumerable<TSource> GetAsyncEnumerable(int index)
  277. {
  278. if (index > nextIndex)
  279. {
  280. return null;
  281. }
  282. // Walk back through the chain of ConcatNIterators looking for the one
  283. // that has its _nextIndex equal to index. If we don't find one, then it
  284. // must be prior to any of them, so call GetEnumerable on the previous
  285. // Concat2Iterator. This avoids a deep recursive call chain.
  286. var current = this;
  287. while (true)
  288. {
  289. if (index == current.nextIndex)
  290. {
  291. return current.next;
  292. }
  293. if (current.previousConcat is ConcatNAsyncIterator<TSource> prevN)
  294. {
  295. current = prevN;
  296. continue;
  297. }
  298. Debug.Assert(current.previousConcat is Concat2AsyncIterator<TSource>);
  299. Debug.Assert(index == 0 || index == 1);
  300. return current.previousConcat.GetAsyncEnumerable(index);
  301. }
  302. }
  303. }
  304. }
  305. }