AppendPrepend.cs 18 KB

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