AppendPrepend.cs 18 KB

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