AppendPrepend.cs 18 KB

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