Concatenate.cs 10 KB

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