AppendPrepend.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 AppendPrepentAsyncIterator<TSource> appendable)
  17. {
  18. return appendable.Append(element);
  19. }
  20. return new AppendPrepend1AsyncIterator<TSource>(source, element, 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 AppendPrepentAsyncIterator<TSource> appendable)
  27. {
  28. return appendable.Prepend(element);
  29. }
  30. return new AppendPrepend1AsyncIterator<TSource>(source, element, false);
  31. }
  32. private abstract class AppendPrepentAsyncIterator<TSource> : AsyncIterator<TSource>, IIListProvider<TSource>
  33. {
  34. protected readonly IAsyncEnumerable<TSource> source;
  35. protected IAsyncEnumerator<TSource> enumerator;
  36. protected AppendPrepentAsyncIterator(IAsyncEnumerable<TSource> source)
  37. {
  38. Debug.Assert(source != null);
  39. this.source = source;
  40. }
  41. protected void GetSourceEnumerator()
  42. {
  43. Debug.Assert(enumerator == null);
  44. enumerator = source.GetAsyncEnumerator();
  45. }
  46. public abstract AppendPrepentAsyncIterator<TSource> Append(TSource item);
  47. public abstract AppendPrepentAsyncIterator<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 Task 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> : 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()
  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 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 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. var en = source.GetAsyncEnumerator();
  168. try
  169. {
  170. while (await en.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  171. {
  172. array[index] = en.Current;
  173. ++index;
  174. }
  175. }
  176. finally
  177. {
  178. await en.DisposeAsync().ConfigureAwait(false);
  179. }
  180. }
  181. if (appending)
  182. {
  183. array[array.Length - 1] = item;
  184. }
  185. return array;
  186. }
  187. public override async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  188. {
  189. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  190. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  191. if (!appending)
  192. {
  193. list.Add(item);
  194. }
  195. var en = source.GetAsyncEnumerator();
  196. try
  197. {
  198. while (await en.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  199. {
  200. list.Add(en.Current);
  201. }
  202. }
  203. finally
  204. {
  205. await en.DisposeAsync().ConfigureAwait(false);
  206. }
  207. if (appending)
  208. {
  209. list.Add(item);
  210. }
  211. return list;
  212. }
  213. public override async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  214. {
  215. if (source is IIListProvider<TSource> listProv)
  216. {
  217. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  218. return count == -1 ? -1 : count + 1;
  219. }
  220. return !onlyIfCheap || source is ICollection<TSource> ? await source.Count(cancellationToken).ConfigureAwait(false) + 1 : -1;
  221. }
  222. }
  223. private sealed class SingleLinkedNode<TSource>
  224. {
  225. public SingleLinkedNode(TSource first, TSource second)
  226. {
  227. Linked = new SingleLinkedNode<TSource>(first);
  228. Item = second;
  229. Count = 2;
  230. }
  231. public SingleLinkedNode(TSource item)
  232. {
  233. Item = item;
  234. Count = 1;
  235. }
  236. private SingleLinkedNode(SingleLinkedNode<TSource> linked, TSource item)
  237. {
  238. Debug.Assert(linked != null);
  239. Linked = linked;
  240. Item = item;
  241. Count = linked.Count + 1;
  242. }
  243. public TSource Item { get; }
  244. public SingleLinkedNode<TSource> Linked { get; }
  245. public int Count { get; }
  246. public SingleLinkedNode<TSource> Add(TSource item) => new SingleLinkedNode<TSource>(this, item);
  247. public IEnumerator<TSource> GetEnumerator()
  248. {
  249. var array = new TSource[Count];
  250. var index = Count;
  251. for (var n = this; n != null; n = n.Linked)
  252. {
  253. --index;
  254. array[index] = n.Item;
  255. }
  256. Debug.Assert(index == 0);
  257. return ((IEnumerable<TSource>)array).GetEnumerator();
  258. }
  259. }
  260. private sealed class AppendPrependNAsyncIterator<TSource> : AppendPrepentAsyncIterator<TSource>
  261. {
  262. private readonly SingleLinkedNode<TSource> prepended;
  263. private readonly SingleLinkedNode<TSource> appended;
  264. private SingleLinkedNode<TSource> node;
  265. public AppendPrependNAsyncIterator(IAsyncEnumerable<TSource> source, SingleLinkedNode<TSource> prepended, SingleLinkedNode<TSource> appended)
  266. : base(source)
  267. {
  268. Debug.Assert(prepended != null || appended != null);
  269. this.prepended = prepended;
  270. this.appended = appended;
  271. }
  272. public override AsyncIterator<TSource> Clone()
  273. {
  274. return new AppendPrependNAsyncIterator<TSource>(source, prepended, appended);
  275. }
  276. int mode;
  277. IEnumerator<TSource> appendedEnumerator;
  278. public override async Task DisposeAsync()
  279. {
  280. if (appendedEnumerator != null)
  281. {
  282. appendedEnumerator.Dispose();
  283. appendedEnumerator = null;
  284. }
  285. await base.DisposeAsync().ConfigureAwait(false);
  286. }
  287. protected override async Task<bool> MoveNextCore()
  288. {
  289. switch (state)
  290. {
  291. case AsyncIteratorState.Allocated:
  292. mode = 1;
  293. state = AsyncIteratorState.Iterating;
  294. goto case AsyncIteratorState.Iterating;
  295. case AsyncIteratorState.Iterating:
  296. switch (mode)
  297. {
  298. case 1:
  299. node = prepended;
  300. mode = 2;
  301. goto case 2;
  302. case 2:
  303. if (node != null)
  304. {
  305. current = node.Item;
  306. node = node.Linked;
  307. return true;
  308. }
  309. GetSourceEnumerator();
  310. mode = 3;
  311. goto case 3;
  312. case 3:
  313. if (await LoadFromEnumeratorAsync().ConfigureAwait(false))
  314. {
  315. return true;
  316. }
  317. if (appended != null)
  318. {
  319. appendedEnumerator = appended.GetEnumerator();
  320. mode = 4;
  321. goto case 4;
  322. }
  323. break;
  324. case 4:
  325. if (appendedEnumerator.MoveNext())
  326. {
  327. current = appendedEnumerator.Current;
  328. return true;
  329. }
  330. break;
  331. }
  332. break;
  333. }
  334. await DisposeAsync().ConfigureAwait(false);
  335. return false;
  336. }
  337. public override AppendPrepentAsyncIterator<TSource> Append(TSource item)
  338. {
  339. return new AppendPrependNAsyncIterator<TSource>(source, prepended, appended != null ? appended.Add(item) : new SingleLinkedNode<TSource>(item));
  340. }
  341. public override AppendPrepentAsyncIterator<TSource> Prepend(TSource item)
  342. {
  343. return new AppendPrependNAsyncIterator<TSource>(source, prepended != null ? prepended.Add(item) : new SingleLinkedNode<TSource>(item), appended);
  344. }
  345. public override async Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  346. {
  347. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  348. if (count == -1)
  349. {
  350. return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
  351. }
  352. var array = new TSource[count];
  353. var index = 0;
  354. for (var n = prepended; n != null; n = n.Linked)
  355. {
  356. array[index] = n.Item;
  357. ++index;
  358. }
  359. if (source is ICollection<TSource> sourceCollection)
  360. {
  361. sourceCollection.CopyTo(array, index);
  362. }
  363. else
  364. {
  365. var en = source.GetAsyncEnumerator();
  366. try
  367. {
  368. while (await en.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  369. {
  370. array[index] = en.Current;
  371. ++index;
  372. }
  373. }
  374. finally
  375. {
  376. await en.DisposeAsync().ConfigureAwait(false);
  377. }
  378. }
  379. index = array.Length;
  380. for (var n = appended; n != null; n = n.Linked)
  381. {
  382. --index;
  383. array[index] = n.Item;
  384. }
  385. return array;
  386. }
  387. public override async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  388. {
  389. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  390. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  391. for (var n = prepended; n != null; n = n.Linked)
  392. {
  393. list.Add(n.Item);
  394. }
  395. var en = source.GetAsyncEnumerator();
  396. try
  397. {
  398. while (await en.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  399. {
  400. list.Add(en.Current);
  401. }
  402. }
  403. finally
  404. {
  405. await en.DisposeAsync().ConfigureAwait(false);
  406. }
  407. if (appended != null)
  408. {
  409. using (var en2 = appended.GetEnumerator())
  410. {
  411. while (en2.MoveNext())
  412. {
  413. list.Add(en2.Current);
  414. }
  415. }
  416. }
  417. return list;
  418. }
  419. public override async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  420. {
  421. if (source is IIListProvider<TSource> listProv)
  422. {
  423. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  424. return count == -1 ? -1 : count + (appended == null ? 0 : appended.Count) + (prepended == null ? 0 : prepended.Count);
  425. }
  426. return !onlyIfCheap || source is ICollection<TSource> ? await source.Count(cancellationToken).ConfigureAwait(false) + (appended == null ? 0 : appended.Count) + (prepended == null ? 0 : prepended.Count) : -1;
  427. }
  428. }
  429. }
  430. }