AppendPrepend.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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> Append<TSource>(this IAsyncEnumerable<TSource> source, TSource element)
  13. {
  14. if (source == null)
  15. throw new ArgumentNullException(nameof(source));
  16. if (source is AppendPrependAsyncIterator<TSource> appendable)
  17. {
  18. return appendable.Append(element);
  19. }
  20. return new AppendPrepend1AsyncIterator<TSource>(source, element, appending: true);
  21. }
  22. public static IAsyncEnumerable<TSource> Prepend<TSource>(this IAsyncEnumerable<TSource> source, TSource element)
  23. {
  24. if (source == null)
  25. throw new ArgumentNullException(nameof(source));
  26. if (source is AppendPrependAsyncIterator<TSource> appendable)
  27. {
  28. return appendable.Prepend(element);
  29. }
  30. return new AppendPrepend1AsyncIterator<TSource>(source, element, appending: false);
  31. }
  32. private abstract class AppendPrependAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  33. {
  34. protected readonly IAsyncEnumerable<TSource> source;
  35. protected IAsyncEnumerator<TSource> enumerator;
  36. protected AppendPrependAsyncIterator(IAsyncEnumerable<TSource> source)
  37. {
  38. Debug.Assert(source != null);
  39. this.source = source;
  40. }
  41. protected void GetSourceEnumerator(CancellationToken cancellationToken)
  42. {
  43. Debug.Assert(enumerator == null);
  44. enumerator = source.GetAsyncEnumerator(cancellationToken);
  45. }
  46. public abstract AppendPrependAsyncIterator<TSource> Append(TSource item);
  47. public abstract AppendPrependAsyncIterator<TSource> Prepend(TSource item);
  48. protected async Task<bool> LoadFromEnumeratorAsync()
  49. {
  50. if (await enumerator.MoveNextAsync().ConfigureAwait(false))
  51. {
  52. current = enumerator.Current;
  53. return true;
  54. }
  55. if (enumerator != null)
  56. {
  57. await enumerator.DisposeAsync().ConfigureAwait(false);
  58. enumerator = null;
  59. }
  60. return false;
  61. }
  62. public override async ValueTask DisposeAsync()
  63. {
  64. if (enumerator != null)
  65. {
  66. await enumerator.DisposeAsync().ConfigureAwait(false);
  67. enumerator = null;
  68. }
  69. await base.DisposeAsync().ConfigureAwait(false);
  70. }
  71. public abstract Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken);
  72. public abstract Task<List<TSource>> ToListAsync(CancellationToken cancellationToken);
  73. public abstract Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken);
  74. }
  75. private sealed class AppendPrepend1AsyncIterator<TSource> : AppendPrependAsyncIterator<TSource>
  76. {
  77. private readonly TSource item;
  78. private readonly bool appending;
  79. bool hasEnumerator;
  80. public AppendPrepend1AsyncIterator(IAsyncEnumerable<TSource> source, TSource item, bool appending)
  81. : base(source)
  82. {
  83. this.item = item;
  84. this.appending = appending;
  85. }
  86. public override AsyncIterator<TSource> Clone()
  87. {
  88. return new AppendPrepend1AsyncIterator<TSource>(source, item, appending);
  89. }
  90. protected override async ValueTask<bool> MoveNextCore(CancellationToken cancellationToken)
  91. {
  92. switch (state)
  93. {
  94. case AsyncIteratorState.Allocated:
  95. hasEnumerator = false;
  96. state = AsyncIteratorState.Iterating;
  97. if (!appending)
  98. {
  99. current = item;
  100. return true;
  101. }
  102. goto case AsyncIteratorState.Iterating;
  103. case AsyncIteratorState.Iterating:
  104. if (!hasEnumerator)
  105. {
  106. GetSourceEnumerator(cancellationToken);
  107. hasEnumerator = true;
  108. }
  109. if (enumerator != null)
  110. {
  111. if (await LoadFromEnumeratorAsync()
  112. .ConfigureAwait(false))
  113. {
  114. return true;
  115. }
  116. if (appending)
  117. {
  118. current = item;
  119. return true;
  120. }
  121. }
  122. break;
  123. }
  124. await DisposeAsync().ConfigureAwait(false);
  125. return false;
  126. }
  127. public override AppendPrependAsyncIterator<TSource> Append(TSource element)
  128. {
  129. if (appending)
  130. {
  131. return new AppendPrependNAsyncIterator<TSource>(source, null, new SingleLinkedNode<TSource>(item).Add(element), prependCount: 0, appendCount: 2);
  132. }
  133. else
  134. {
  135. return new AppendPrependNAsyncIterator<TSource>(source, new SingleLinkedNode<TSource>(item), new SingleLinkedNode<TSource>(element), prependCount: 1, appendCount: 1);
  136. }
  137. }
  138. public override AppendPrependAsyncIterator<TSource> Prepend(TSource element)
  139. {
  140. if (appending)
  141. {
  142. return new AppendPrependNAsyncIterator<TSource>(source, new SingleLinkedNode<TSource>(element), new SingleLinkedNode<TSource>(item), prependCount: 1, appendCount: 1);
  143. }
  144. else
  145. {
  146. return new AppendPrependNAsyncIterator<TSource>(source, new SingleLinkedNode<TSource>(item).Add(element), null, prependCount: 2, appendCount: 0);
  147. }
  148. }
  149. public override async Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  150. {
  151. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  152. if (count == -1)
  153. {
  154. return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
  155. }
  156. var array = new TSource[count];
  157. int index;
  158. if (appending)
  159. {
  160. index = 0;
  161. }
  162. else
  163. {
  164. array[0] = item;
  165. index = 1;
  166. }
  167. if (source is ICollection<TSource> sourceCollection)
  168. {
  169. sourceCollection.CopyTo(array, index);
  170. }
  171. else
  172. {
  173. var en = source.GetAsyncEnumerator(cancellationToken);
  174. try
  175. {
  176. while (await en.MoveNextAsync().ConfigureAwait(false))
  177. {
  178. array[index] = en.Current;
  179. ++index;
  180. }
  181. }
  182. finally
  183. {
  184. await en.DisposeAsync().ConfigureAwait(false);
  185. }
  186. }
  187. if (appending)
  188. {
  189. array[array.Length - 1] = item;
  190. }
  191. return array;
  192. }
  193. public override async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  194. {
  195. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  196. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  197. if (!appending)
  198. {
  199. list.Add(item);
  200. }
  201. var en = source.GetAsyncEnumerator(cancellationToken);
  202. try
  203. {
  204. while (await en.MoveNextAsync().ConfigureAwait(false))
  205. {
  206. list.Add(en.Current);
  207. }
  208. }
  209. finally
  210. {
  211. await en.DisposeAsync().ConfigureAwait(false);
  212. }
  213. if (appending)
  214. {
  215. list.Add(item);
  216. }
  217. return list;
  218. }
  219. public override async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  220. {
  221. if (source is IAsyncIListProvider<TSource> listProv)
  222. {
  223. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  224. return count == -1 ? -1 : count + 1;
  225. }
  226. return !onlyIfCheap || source is ICollection<TSource> ? await source.Count(cancellationToken).ConfigureAwait(false) + 1 : -1;
  227. }
  228. }
  229. private sealed class AppendPrependNAsyncIterator<TSource> : AppendPrependAsyncIterator<TSource>
  230. {
  231. private readonly SingleLinkedNode<TSource> prepended;
  232. private readonly SingleLinkedNode<TSource> appended;
  233. private readonly int prependCount;
  234. private readonly int appendCount;
  235. private SingleLinkedNode<TSource> node;
  236. public AppendPrependNAsyncIterator(IAsyncEnumerable<TSource> source, SingleLinkedNode<TSource> prepended, SingleLinkedNode<TSource> appended, int prependCount, int appendCount)
  237. : base(source)
  238. {
  239. Debug.Assert(prepended != null || appended != null);
  240. Debug.Assert(prependCount > 0 || appendCount > 0);
  241. Debug.Assert(prependCount + appendCount >= 2);
  242. Debug.Assert((prepended?.GetCount() ?? 0) == prependCount);
  243. Debug.Assert((appended?.GetCount() ?? 0) == appendCount);
  244. this.prepended = prepended;
  245. this.appended = appended;
  246. this.prependCount = prependCount;
  247. this.appendCount = appendCount;
  248. }
  249. public override AsyncIterator<TSource> Clone()
  250. {
  251. return new AppendPrependNAsyncIterator<TSource>(source, prepended, appended, prependCount, appendCount);
  252. }
  253. int mode;
  254. IEnumerator<TSource> appendedEnumerator;
  255. public override async ValueTask DisposeAsync()
  256. {
  257. if (appendedEnumerator != null)
  258. {
  259. appendedEnumerator.Dispose();
  260. appendedEnumerator = null;
  261. }
  262. await base.DisposeAsync().ConfigureAwait(false);
  263. }
  264. protected override async ValueTask<bool> MoveNextCore(CancellationToken cancellationToken)
  265. {
  266. switch (state)
  267. {
  268. case AsyncIteratorState.Allocated:
  269. mode = 1;
  270. state = AsyncIteratorState.Iterating;
  271. goto case AsyncIteratorState.Iterating;
  272. case AsyncIteratorState.Iterating:
  273. switch (mode)
  274. {
  275. case 1:
  276. node = prepended;
  277. mode = 2;
  278. goto case 2;
  279. case 2:
  280. if (node != null)
  281. {
  282. current = node.Item;
  283. node = node.Linked;
  284. return true;
  285. }
  286. GetSourceEnumerator(cancellationToken);
  287. mode = 3;
  288. goto case 3;
  289. case 3:
  290. if (await LoadFromEnumeratorAsync().ConfigureAwait(false))
  291. {
  292. return true;
  293. }
  294. if (appended != null)
  295. {
  296. appendedEnumerator = appended.GetEnumerator(appendCount);
  297. mode = 4;
  298. goto case 4;
  299. }
  300. break;
  301. case 4:
  302. if (appendedEnumerator.MoveNext())
  303. {
  304. current = appendedEnumerator.Current;
  305. return true;
  306. }
  307. break;
  308. }
  309. break;
  310. }
  311. await DisposeAsync().ConfigureAwait(false);
  312. return false;
  313. }
  314. public override AppendPrependAsyncIterator<TSource> Append(TSource item)
  315. {
  316. var res = appended != null ? appended.Add(item) : new SingleLinkedNode<TSource>(item);
  317. return new AppendPrependNAsyncIterator<TSource>(source, prepended, res, prependCount, appendCount + 1);
  318. }
  319. public override AppendPrependAsyncIterator<TSource> Prepend(TSource item)
  320. {
  321. var res = prepended != null ? prepended.Add(item) : new SingleLinkedNode<TSource>(item);
  322. return new AppendPrependNAsyncIterator<TSource>(source, res, appended, prependCount + 1, appendCount);
  323. }
  324. public override async Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  325. {
  326. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  327. if (count == -1)
  328. {
  329. return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
  330. }
  331. var array = new TSource[count];
  332. var index = 0;
  333. for (var n = prepended; n != null; n = n.Linked)
  334. {
  335. array[index] = n.Item;
  336. ++index;
  337. }
  338. if (source is ICollection<TSource> sourceCollection)
  339. {
  340. sourceCollection.CopyTo(array, index);
  341. }
  342. else
  343. {
  344. var en = source.GetAsyncEnumerator(cancellationToken);
  345. try
  346. {
  347. while (await en.MoveNextAsync().ConfigureAwait(false))
  348. {
  349. array[index] = en.Current;
  350. ++index;
  351. }
  352. }
  353. finally
  354. {
  355. await en.DisposeAsync().ConfigureAwait(false);
  356. }
  357. }
  358. index = array.Length;
  359. for (var n = appended; n != null; n = n.Linked)
  360. {
  361. --index;
  362. array[index] = n.Item;
  363. }
  364. return array;
  365. }
  366. public override async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  367. {
  368. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  369. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  370. for (var n = prepended; n != null; n = n.Linked)
  371. {
  372. list.Add(n.Item);
  373. }
  374. var en = source.GetAsyncEnumerator(cancellationToken);
  375. try
  376. {
  377. while (await en.MoveNextAsync().ConfigureAwait(false))
  378. {
  379. list.Add(en.Current);
  380. }
  381. }
  382. finally
  383. {
  384. await en.DisposeAsync().ConfigureAwait(false);
  385. }
  386. if (appended != null)
  387. {
  388. using (var en2 = appended.GetEnumerator(appendCount))
  389. {
  390. while (en2.MoveNext())
  391. {
  392. list.Add(en2.Current);
  393. }
  394. }
  395. }
  396. return list;
  397. }
  398. public override async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  399. {
  400. if (source is IAsyncIListProvider<TSource> listProv)
  401. {
  402. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  403. return count == -1 ? -1 : count + appendCount + prependCount;
  404. }
  405. return !onlyIfCheap || source is ICollection<TSource> ? await source.Count(cancellationToken).ConfigureAwait(false) + appendCount + prependCount : -1;
  406. }
  407. }
  408. }
  409. }