Concat.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  13. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.concat?view=net-9.0-pp
  14. /// <summary>
  15. /// Concatenates the second async-enumerable sequence to the first async-enumerable sequence upon successful termination of the first.
  16. /// </summary>
  17. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  18. /// <param name="first">First async-enumerable sequence.</param>
  19. /// <param name="second">Second async-enumerable sequence.</param>
  20. /// <returns>An async-enumerable sequence that contains the elements of the first sequence, followed by those of the second the sequence.</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="first"/> or <paramref name="second"/> is null.</exception>
  22. public static IAsyncEnumerable<TSource> Concat<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  23. {
  24. if (first == null)
  25. throw Error.ArgumentNull(nameof(first));
  26. if (second == null)
  27. throw Error.ArgumentNull(nameof(second));
  28. return first is ConcatAsyncIterator<TSource> concatFirst ?
  29. concatFirst.Concat(second) :
  30. new Concat2AsyncIterator<TSource>(first, second);
  31. }
  32. private sealed class Concat2AsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  33. {
  34. private readonly IAsyncEnumerable<TSource> _first;
  35. private readonly IAsyncEnumerable<TSource> _second;
  36. internal Concat2AsyncIterator(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  37. {
  38. _first = first;
  39. _second = second;
  40. }
  41. public override AsyncIteratorBase<TSource> Clone()
  42. {
  43. return new Concat2AsyncIterator<TSource>(_first, _second);
  44. }
  45. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  46. {
  47. return new ConcatNAsyncIterator<TSource>(this, next, 2);
  48. }
  49. internal override IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index)
  50. {
  51. return index switch
  52. {
  53. 0 => _first,
  54. 1 => _second,
  55. _ => null,
  56. };
  57. }
  58. }
  59. private abstract class ConcatAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  60. {
  61. private int _counter;
  62. private IAsyncEnumerator<TSource>? _enumerator;
  63. public ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  64. {
  65. return AsyncEnumerableHelpers.ToArray(this, cancellationToken);
  66. }
  67. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  68. {
  69. cancellationToken.ThrowIfCancellationRequested();
  70. var list = new List<TSource>();
  71. for (var i = 0; ; i++)
  72. {
  73. var source = GetAsyncEnumerable(i);
  74. if (source == null)
  75. {
  76. break;
  77. }
  78. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  79. {
  80. list.Add(item);
  81. }
  82. }
  83. return list;
  84. }
  85. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  86. {
  87. if (onlyIfCheap)
  88. {
  89. return new ValueTask<int>(-1);
  90. }
  91. return Core();
  92. async ValueTask<int> Core()
  93. {
  94. cancellationToken.ThrowIfCancellationRequested();
  95. var count = 0;
  96. for (var i = 0; ; i++)
  97. {
  98. var source = GetAsyncEnumerable(i);
  99. if (source == null)
  100. {
  101. break;
  102. }
  103. checked
  104. {
  105. count += await source.CountAsync(cancellationToken).ConfigureAwait(false);
  106. }
  107. }
  108. return count;
  109. }
  110. }
  111. public override async ValueTask DisposeAsync()
  112. {
  113. if (_enumerator != null)
  114. {
  115. await _enumerator.DisposeAsync().ConfigureAwait(false);
  116. _enumerator = null;
  117. }
  118. await base.DisposeAsync().ConfigureAwait(false);
  119. }
  120. protected override async ValueTask<bool> MoveNextCore()
  121. {
  122. if (_state == AsyncIteratorState.Allocated)
  123. {
  124. _enumerator = GetAsyncEnumerable(0)!.GetAsyncEnumerator(_cancellationToken);
  125. _state = AsyncIteratorState.Iterating;
  126. _counter = 2;
  127. }
  128. if (_state == AsyncIteratorState.Iterating)
  129. {
  130. while (true)
  131. {
  132. if (await _enumerator!.MoveNextAsync().ConfigureAwait(false))
  133. {
  134. _current = _enumerator.Current;
  135. return true;
  136. }
  137. //
  138. // NB: This is simply to match the logic of
  139. // https://github.com/dotnet/corefx/blob/f7539b726c4bc2385b7f49e5751c1cff2f2c7368/src/System.Linq/src/System/Linq/Concat.cs#L240
  140. //
  141. var next = GetAsyncEnumerable(_counter++ - 1);
  142. if (next != null)
  143. {
  144. await _enumerator.DisposeAsync().ConfigureAwait(false);
  145. _enumerator = next.GetAsyncEnumerator(_cancellationToken);
  146. continue;
  147. }
  148. await DisposeAsync().ConfigureAwait(false);
  149. break;
  150. }
  151. }
  152. return false;
  153. }
  154. internal abstract ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next);
  155. internal abstract IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index);
  156. }
  157. // To handle chains of >= 3 sources, we chain the concat iterators together and allow
  158. // GetEnumerable to fetch enumerables from the previous sources. This means that rather
  159. // than each MoveNext/Current calls having to traverse all of the previous sources, we
  160. // only have to traverse all of the previous sources once per chained enumerable. An
  161. // alternative would be to use an array to store all of the enumerables, but this has
  162. // a much better memory profile and without much additional run-time cost.
  163. private sealed class ConcatNAsyncIterator<TSource> : ConcatAsyncIterator<TSource>
  164. {
  165. private readonly IAsyncEnumerable<TSource> _next;
  166. private readonly int _nextIndex;
  167. private readonly ConcatAsyncIterator<TSource> _previousConcat;
  168. internal ConcatNAsyncIterator(ConcatAsyncIterator<TSource> previousConcat, IAsyncEnumerable<TSource> next, int nextIndex)
  169. {
  170. Debug.Assert(nextIndex >= 2);
  171. _previousConcat = previousConcat;
  172. _next = next;
  173. _nextIndex = nextIndex;
  174. }
  175. public override AsyncIteratorBase<TSource> Clone()
  176. {
  177. return new ConcatNAsyncIterator<TSource>(_previousConcat, _next, _nextIndex);
  178. }
  179. internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
  180. {
  181. if (_nextIndex == int.MaxValue - 2)
  182. {
  183. // In the unlikely case of this many concatenations, if we produced a ConcatNIterator
  184. // with int.MaxValue then state would overflow before it matched it's index.
  185. // So we use the naïve approach of just having a left and right sequence.
  186. return new Concat2AsyncIterator<TSource>(this, next);
  187. }
  188. return new ConcatNAsyncIterator<TSource>(this, next, _nextIndex + 1);
  189. }
  190. internal override IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index)
  191. {
  192. if (index > _nextIndex)
  193. {
  194. return null;
  195. }
  196. // Walk back through the chain of ConcatNIterators looking for the one
  197. // that has its _nextIndex equal to index. If we don't find one, then it
  198. // must be prior to any of them, so call GetEnumerable on the previous
  199. // Concat2Iterator. This avoids a deep recursive call chain.
  200. var current = this;
  201. while (true)
  202. {
  203. if (index == current._nextIndex)
  204. {
  205. return current._next;
  206. }
  207. if (current._previousConcat is ConcatNAsyncIterator<TSource> prevN)
  208. {
  209. current = prevN;
  210. continue;
  211. }
  212. Debug.Assert(current._previousConcat is Concat2AsyncIterator<TSource>);
  213. Debug.Assert(index == 0 || index == 1);
  214. return current._previousConcat.GetAsyncEnumerable(index);
  215. }
  216. }
  217. }
  218. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  219. }
  220. }