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