AppendPrepend.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 Error.ArgumentNull(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 Error.ArgumentNull(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. _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. private bool _hasEnumerator;
  80. public AppendPrepend1AsyncIterator(IAsyncEnumerable<TSource> source, TSource item, bool appending)
  81. : base(source)
  82. {
  83. _item = item;
  84. _appending = appending;
  85. }
  86. public override AsyncIteratorBase<TSource> Clone()
  87. {
  88. return new AppendPrepend1AsyncIterator<TSource>(_source, _item, _appending);
  89. }
  90. protected override async ValueTask<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(_cancellationToken);
  107. _hasEnumerator = true;
  108. }
  109. if (_enumerator != null)
  110. {
  111. if (await LoadFromEnumeratorAsync().ConfigureAwait(false))
  112. {
  113. return true;
  114. }
  115. if (_appending)
  116. {
  117. _current = _item;
  118. return true;
  119. }
  120. }
  121. break;
  122. }
  123. await DisposeAsync().ConfigureAwait(false);
  124. return false;
  125. }
  126. public override AppendPrependAsyncIterator<TSource> Append(TSource element)
  127. {
  128. if (_appending)
  129. {
  130. return new AppendPrependNAsyncIterator<TSource>(_source, null, new SingleLinkedNode<TSource>(_item).Add(element), prependCount: 0, appendCount: 2);
  131. }
  132. else
  133. {
  134. return new AppendPrependNAsyncIterator<TSource>(_source, new SingleLinkedNode<TSource>(_item), new SingleLinkedNode<TSource>(element), prependCount: 1, appendCount: 1);
  135. }
  136. }
  137. public override AppendPrependAsyncIterator<TSource> Prepend(TSource element)
  138. {
  139. if (_appending)
  140. {
  141. return new AppendPrependNAsyncIterator<TSource>(_source, new SingleLinkedNode<TSource>(element), new SingleLinkedNode<TSource>(_item), prependCount: 1, appendCount: 1);
  142. }
  143. else
  144. {
  145. return new AppendPrependNAsyncIterator<TSource>(_source, new SingleLinkedNode<TSource>(_item).Add(element), null, prependCount: 2, appendCount: 0);
  146. }
  147. }
  148. public override async Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  149. {
  150. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  151. if (count == -1)
  152. {
  153. return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
  154. }
  155. var array = new TSource[count];
  156. int index;
  157. if (_appending)
  158. {
  159. index = 0;
  160. }
  161. else
  162. {
  163. array[0] = _item;
  164. index = 1;
  165. }
  166. if (_source is ICollection<TSource> sourceCollection)
  167. {
  168. sourceCollection.CopyTo(array, index);
  169. }
  170. else
  171. {
  172. var en = _source.GetAsyncEnumerator(cancellationToken);
  173. try
  174. {
  175. while (await en.MoveNextAsync().ConfigureAwait(false))
  176. {
  177. array[index] = en.Current;
  178. ++index;
  179. }
  180. }
  181. finally
  182. {
  183. await en.DisposeAsync().ConfigureAwait(false);
  184. }
  185. }
  186. if (_appending)
  187. {
  188. array[array.Length - 1] = _item;
  189. }
  190. return array;
  191. }
  192. public override async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  193. {
  194. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  195. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  196. if (!_appending)
  197. {
  198. list.Add(_item);
  199. }
  200. var en = _source.GetAsyncEnumerator(cancellationToken);
  201. try
  202. {
  203. while (await en.MoveNextAsync().ConfigureAwait(false))
  204. {
  205. list.Add(en.Current);
  206. }
  207. }
  208. finally
  209. {
  210. await en.DisposeAsync().ConfigureAwait(false);
  211. }
  212. if (_appending)
  213. {
  214. list.Add(_item);
  215. }
  216. return list;
  217. }
  218. public override async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  219. {
  220. if (_source is IAsyncIListProvider<TSource> listProv)
  221. {
  222. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  223. return count == -1 ? -1 : count + 1;
  224. }
  225. return !onlyIfCheap || _source is ICollection<TSource> ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) + 1 : -1;
  226. }
  227. }
  228. private sealed class AppendPrependNAsyncIterator<TSource> : AppendPrependAsyncIterator<TSource>
  229. {
  230. private readonly SingleLinkedNode<TSource> _prepended;
  231. private readonly SingleLinkedNode<TSource> _appended;
  232. private readonly int _prependCount;
  233. private readonly int _appendCount;
  234. private SingleLinkedNode<TSource> _node;
  235. private int _mode;
  236. private IEnumerator<TSource> _appendedEnumerator;
  237. public AppendPrependNAsyncIterator(IAsyncEnumerable<TSource> source, SingleLinkedNode<TSource> prepended, SingleLinkedNode<TSource> appended, int prependCount, int appendCount)
  238. : base(source)
  239. {
  240. Debug.Assert(prepended != null || appended != null);
  241. Debug.Assert(prependCount > 0 || appendCount > 0);
  242. Debug.Assert(prependCount + appendCount >= 2);
  243. Debug.Assert((prepended?.GetCount() ?? 0) == prependCount);
  244. Debug.Assert((appended?.GetCount() ?? 0) == appendCount);
  245. _prepended = prepended;
  246. _appended = appended;
  247. _prependCount = prependCount;
  248. _appendCount = appendCount;
  249. }
  250. public override AsyncIteratorBase<TSource> Clone()
  251. {
  252. return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, _appended, _prependCount, _appendCount);
  253. }
  254. public override async ValueTask DisposeAsync()
  255. {
  256. if (_appendedEnumerator != null)
  257. {
  258. _appendedEnumerator.Dispose();
  259. _appendedEnumerator = null;
  260. }
  261. await base.DisposeAsync().ConfigureAwait(false);
  262. }
  263. protected override async ValueTask<bool> MoveNextCore()
  264. {
  265. switch (_state)
  266. {
  267. case AsyncIteratorState.Allocated:
  268. _mode = 1;
  269. _state = AsyncIteratorState.Iterating;
  270. goto case AsyncIteratorState.Iterating;
  271. case AsyncIteratorState.Iterating:
  272. switch (_mode)
  273. {
  274. case 1:
  275. _node = _prepended;
  276. _mode = 2;
  277. goto case 2;
  278. case 2:
  279. if (_node != null)
  280. {
  281. _current = _node.Item;
  282. _node = _node.Linked;
  283. return true;
  284. }
  285. GetSourceEnumerator(_cancellationToken);
  286. _mode = 3;
  287. goto case 3;
  288. case 3:
  289. if (await LoadFromEnumeratorAsync().ConfigureAwait(false))
  290. {
  291. return true;
  292. }
  293. if (_appended != null)
  294. {
  295. _appendedEnumerator = _appended.GetEnumerator(_appendCount);
  296. _mode = 4;
  297. goto case 4;
  298. }
  299. break;
  300. case 4:
  301. if (_appendedEnumerator.MoveNext())
  302. {
  303. _current = _appendedEnumerator.Current;
  304. return true;
  305. }
  306. break;
  307. }
  308. break;
  309. }
  310. await DisposeAsync().ConfigureAwait(false);
  311. return false;
  312. }
  313. public override AppendPrependAsyncIterator<TSource> Append(TSource item)
  314. {
  315. var res = _appended != null ? _appended.Add(item) : new SingleLinkedNode<TSource>(item);
  316. return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, res, _prependCount, _appendCount + 1);
  317. }
  318. public override AppendPrependAsyncIterator<TSource> Prepend(TSource item)
  319. {
  320. var res = _prepended != null ? _prepended.Add(item) : new SingleLinkedNode<TSource>(item);
  321. return new AppendPrependNAsyncIterator<TSource>(_source, res, _appended, _prependCount + 1, _appendCount);
  322. }
  323. public override async Task<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  324. {
  325. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  326. if (count == -1)
  327. {
  328. return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
  329. }
  330. var array = new TSource[count];
  331. var index = 0;
  332. for (var n = _prepended; n != null; n = n.Linked)
  333. {
  334. array[index] = n.Item;
  335. ++index;
  336. }
  337. if (_source is ICollection<TSource> sourceCollection)
  338. {
  339. sourceCollection.CopyTo(array, index);
  340. }
  341. else
  342. {
  343. var en = _source.GetAsyncEnumerator(cancellationToken);
  344. try
  345. {
  346. while (await en.MoveNextAsync().ConfigureAwait(false))
  347. {
  348. array[index] = en.Current;
  349. ++index;
  350. }
  351. }
  352. finally
  353. {
  354. await en.DisposeAsync().ConfigureAwait(false);
  355. }
  356. }
  357. index = array.Length;
  358. for (var n = _appended; n != null; n = n.Linked)
  359. {
  360. --index;
  361. array[index] = n.Item;
  362. }
  363. return array;
  364. }
  365. public override async Task<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  366. {
  367. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  368. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  369. for (var n = _prepended; n != null; n = n.Linked)
  370. {
  371. list.Add(n.Item);
  372. }
  373. var en = _source.GetAsyncEnumerator(cancellationToken);
  374. try
  375. {
  376. while (await en.MoveNextAsync().ConfigureAwait(false))
  377. {
  378. list.Add(en.Current);
  379. }
  380. }
  381. finally
  382. {
  383. await en.DisposeAsync().ConfigureAwait(false);
  384. }
  385. if (_appended != null)
  386. {
  387. using (var en2 = _appended.GetEnumerator(_appendCount))
  388. {
  389. while (en2.MoveNext())
  390. {
  391. list.Add(en2.Current);
  392. }
  393. }
  394. }
  395. return list;
  396. }
  397. public override async Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  398. {
  399. if (_source is IAsyncIListProvider<TSource> listProv)
  400. {
  401. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  402. return count == -1 ? -1 : count + _appendCount + _prependCount;
  403. }
  404. return !onlyIfCheap || _source is ICollection<TSource> ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) + _appendCount + _prependCount : -1;
  405. }
  406. }
  407. }
  408. }