Concatenate.cs 13 KB

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