Concat.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 Error.ArgumentNull(nameof(first));
  16. if (second == null)
  17. throw Error.ArgumentNull(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 AsyncIteratorBase<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 ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  59. {
  60. return AsyncEnumerableHelpers.ToArray(this, cancellationToken);
  61. }
  62. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  63. {
  64. cancellationToken.ThrowIfCancellationRequested();
  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. #if CSHARP8 && AETOR_HAS_CT // CS0656 Missing compiler required member 'System.Collections.Generic.IAsyncEnumerable`1.GetAsyncEnumerator'
  74. await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  75. {
  76. list.Add(item);
  77. }
  78. #else
  79. var e = source.GetAsyncEnumerator(cancellationToken);
  80. try
  81. {
  82. while (await e.MoveNextAsync().ConfigureAwait(false))
  83. {
  84. list.Add(e.Current);
  85. }
  86. }
  87. finally
  88. {
  89. await e.DisposeAsync().ConfigureAwait(false);
  90. }
  91. #endif
  92. }
  93. return list;
  94. }
  95. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  96. {
  97. if (onlyIfCheap)
  98. {
  99. return new ValueTask<int>(-1);
  100. }
  101. return Core();
  102. async ValueTask<int> Core()
  103. {
  104. cancellationToken.ThrowIfCancellationRequested();
  105. var count = 0;
  106. for (var i = 0; ; i++)
  107. {
  108. var source = GetAsyncEnumerable(i);
  109. if (source == null)
  110. {
  111. break;
  112. }
  113. checked
  114. {
  115. count += await source.CountAsync(cancellationToken).ConfigureAwait(false);
  116. }
  117. }
  118. return count;
  119. }
  120. }
  121. public override async ValueTask DisposeAsync()
  122. {
  123. if (_enumerator != null)
  124. {
  125. await _enumerator.DisposeAsync().ConfigureAwait(false);
  126. _enumerator = null;
  127. }
  128. await base.DisposeAsync().ConfigureAwait(false);
  129. }
  130. protected override async ValueTask<bool> MoveNextCore()
  131. {
  132. if (_state == AsyncIteratorState.Allocated)
  133. {
  134. _enumerator = GetAsyncEnumerable(0).GetAsyncEnumerator(_cancellationToken);
  135. _state = AsyncIteratorState.Iterating;
  136. _counter = 2;
  137. }
  138. if (_state == AsyncIteratorState.Iterating)
  139. {
  140. while (true)
  141. {
  142. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  143. {
  144. _current = _enumerator.Current;
  145. return true;
  146. }
  147. //
  148. // NB: This is simply to match the logic of
  149. // https://github.com/dotnet/corefx/blob/f7539b726c4bc2385b7f49e5751c1cff2f2c7368/src/System.Linq/src/System/Linq/Concat.cs#L240
  150. //
  151. var next = GetAsyncEnumerable(_counter++ - 1);
  152. if (next != null)
  153. {
  154. await _enumerator.DisposeAsync().ConfigureAwait(false);
  155. _enumerator = next.GetAsyncEnumerator(_cancellationToken);
  156. continue;
  157. }
  158. await DisposeAsync().ConfigureAwait(false);
  159. break;
  160. }
  161. }
  162. return false;
  163. }
  164. internal abstract ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next);
  165. internal abstract IAsyncEnumerable<TSource> GetAsyncEnumerable(int index);
  166. }
  167. // To handle chains of >= 3 sources, we chain the concat iterators together and allow
  168. // GetEnumerable to fetch enumerables from the previous sources. This means that rather
  169. // than each MoveNext/Current calls having to traverse all of the previous sources, we
  170. // only have to traverse all of the previous sources once per chained enumerable. An
  171. // alternative would be to use an array to store all of the enumerables, but this has
  172. // a much better memory profile and without much additional run-time cost.
  173. private sealed class ConcatNAsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  174. {
  175. private readonly IAsyncEnumerable<TSource> _next;
  176. private readonly int _nextIndex;
  177. private readonly ConcatAsyncIterator<TSource> _previousConcat;
  178. internal ConcatNAsyncIterator(ConcatAsyncIterator<TSource> previousConcat, IAsyncEnumerable<TSource> next, int nextIndex)
  179. {
  180. Debug.Assert(previousConcat != null);
  181. Debug.Assert(next != null);
  182. Debug.Assert(nextIndex >= 2);
  183. _previousConcat = previousConcat;
  184. _next = next;
  185. _nextIndex = nextIndex;
  186. }
  187. public override AsyncIteratorBase<TSource> Clone()
  188. {
  189. return new ConcatNAsyncIterator<TSource>(_previousConcat, _next, _nextIndex);
  190. }
  191. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  192. {
  193. if (_nextIndex == int.MaxValue - 2)
  194. {
  195. // In the unlikely case of this many concatenations, if we produced a ConcatNIterator
  196. // with int.MaxValue then state would overflow before it matched it's index.
  197. // So we use the naïve approach of just having a left and right sequence.
  198. return new Concat2AsyncIterator<TSource>(this, next);
  199. }
  200. return new ConcatNAsyncIterator<TSource>(this, next, _nextIndex + 1);
  201. }
  202. internal override IAsyncEnumerable<TSource> GetAsyncEnumerable(int index)
  203. {
  204. if (index > _nextIndex)
  205. {
  206. return null;
  207. }
  208. // Walk back through the chain of ConcatNIterators looking for the one
  209. // that has its _nextIndex equal to index. If we don't find one, then it
  210. // must be prior to any of them, so call GetEnumerable on the previous
  211. // Concat2Iterator. This avoids a deep recursive call chain.
  212. var current = this;
  213. while (true)
  214. {
  215. if (index == current._nextIndex)
  216. {
  217. return current._next;
  218. }
  219. if (current._previousConcat is ConcatNAsyncIterator<TSource> prevN)
  220. {
  221. current = prevN;
  222. continue;
  223. }
  224. Debug.Assert(current._previousConcat is Concat2AsyncIterator<TSource>);
  225. Debug.Assert(index == 0 || index == 1);
  226. return current._previousConcat.GetAsyncEnumerable(index);
  227. }
  228. }
  229. }
  230. }
  231. }