AppendPrepend.cs 19 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;
  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. #if USE_AWAIT_FOREACH
  175. await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  176. {
  177. array[index] = item;
  178. ++index;
  179. }
  180. #else
  181. var en = _source.GetAsyncEnumerator(cancellationToken);
  182. try
  183. {
  184. while (await en.MoveNextAsync().ConfigureAwait(false))
  185. {
  186. array[index] = en.Current;
  187. ++index;
  188. }
  189. }
  190. finally
  191. {
  192. await en.DisposeAsync().ConfigureAwait(false);
  193. }
  194. #endif
  195. }
  196. if (_appending)
  197. {
  198. array[array.Length - 1] = _item;
  199. }
  200. return array;
  201. }
  202. public override async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  203. {
  204. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  205. cancellationToken.ThrowIfCancellationRequested();
  206. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  207. if (!_appending)
  208. {
  209. list.Add(_item);
  210. }
  211. #if USE_AWAIT_FOREACH
  212. await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  213. {
  214. list.Add(item);
  215. }
  216. #else
  217. var en = _source.GetAsyncEnumerator(cancellationToken);
  218. try
  219. {
  220. while (await en.MoveNextAsync().ConfigureAwait(false))
  221. {
  222. list.Add(en.Current);
  223. }
  224. }
  225. finally
  226. {
  227. await en.DisposeAsync().ConfigureAwait(false);
  228. }
  229. #endif
  230. if (_appending)
  231. {
  232. list.Add(_item);
  233. }
  234. return list;
  235. }
  236. public override async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  237. {
  238. if (_source is IAsyncIListProvider<TSource> listProv)
  239. {
  240. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  241. return count == -1 ? -1 : count + 1;
  242. }
  243. return !onlyIfCheap || _source is ICollection<TSource> || _source is ICollection ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) + 1 : -1;
  244. }
  245. }
  246. private sealed class AppendPrependNAsyncIterator<TSource> : AppendPrependAsyncIterator<TSource>
  247. {
  248. private readonly SingleLinkedNode<TSource> _prepended;
  249. private readonly SingleLinkedNode<TSource> _appended;
  250. private readonly int _prependCount;
  251. private readonly int _appendCount;
  252. private SingleLinkedNode<TSource> _node;
  253. private int _mode;
  254. private IEnumerator<TSource> _appendedEnumerator;
  255. public AppendPrependNAsyncIterator(IAsyncEnumerable<TSource> source, SingleLinkedNode<TSource> prepended, SingleLinkedNode<TSource> appended, int prependCount, int appendCount)
  256. : base(source)
  257. {
  258. Debug.Assert(prepended != null || appended != null);
  259. Debug.Assert(prependCount > 0 || appendCount > 0);
  260. Debug.Assert(prependCount + appendCount >= 2);
  261. Debug.Assert((prepended?.GetCount() ?? 0) == prependCount);
  262. Debug.Assert((appended?.GetCount() ?? 0) == appendCount);
  263. _prepended = prepended;
  264. _appended = appended;
  265. _prependCount = prependCount;
  266. _appendCount = appendCount;
  267. }
  268. public override AsyncIteratorBase<TSource> Clone()
  269. {
  270. return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, _appended, _prependCount, _appendCount);
  271. }
  272. public override async ValueTask DisposeAsync()
  273. {
  274. if (_appendedEnumerator != null)
  275. {
  276. _appendedEnumerator.Dispose();
  277. _appendedEnumerator = null;
  278. }
  279. await base.DisposeAsync().ConfigureAwait(false);
  280. }
  281. protected override async ValueTask<bool> MoveNextCore()
  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(_cancellationToken);
  304. _mode = 3;
  305. goto case 3;
  306. case 3:
  307. if (await LoadFromEnumeratorAsync().ConfigureAwait(false))
  308. {
  309. return true;
  310. }
  311. if (_appended != null)
  312. {
  313. _appendedEnumerator = _appended.GetEnumerator(_appendCount);
  314. _mode = 4;
  315. goto case 4;
  316. }
  317. break;
  318. case 4:
  319. if (_appendedEnumerator.MoveNext())
  320. {
  321. _current = _appendedEnumerator.Current;
  322. return true;
  323. }
  324. break;
  325. }
  326. break;
  327. }
  328. await DisposeAsync().ConfigureAwait(false);
  329. return false;
  330. }
  331. public override AppendPrependAsyncIterator<TSource> Append(TSource item)
  332. {
  333. var res = _appended != null ? _appended.Add(item) : new SingleLinkedNode<TSource>(item);
  334. return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, res, _prependCount, _appendCount + 1);
  335. }
  336. public override AppendPrependAsyncIterator<TSource> Prepend(TSource item)
  337. {
  338. var res = _prepended != null ? _prepended.Add(item) : new SingleLinkedNode<TSource>(item);
  339. return new AppendPrependNAsyncIterator<TSource>(_source, res, _appended, _prependCount + 1, _appendCount);
  340. }
  341. public override async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  342. {
  343. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  344. if (count == -1)
  345. {
  346. return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
  347. }
  348. var array = new TSource[count];
  349. var index = 0;
  350. for (var n = _prepended; n != null; n = n.Linked)
  351. {
  352. array[index] = n.Item;
  353. ++index;
  354. }
  355. if (_source is ICollection<TSource> sourceCollection)
  356. {
  357. sourceCollection.CopyTo(array, index);
  358. }
  359. else
  360. {
  361. #if USE_AWAIT_FOREACH
  362. await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  363. {
  364. array[index] = item;
  365. ++index;
  366. }
  367. #else
  368. var en = _source.GetAsyncEnumerator(cancellationToken);
  369. try
  370. {
  371. while (await en.MoveNextAsync().ConfigureAwait(false))
  372. {
  373. array[index] = en.Current;
  374. ++index;
  375. }
  376. }
  377. finally
  378. {
  379. await en.DisposeAsync().ConfigureAwait(false);
  380. }
  381. #endif
  382. }
  383. index = array.Length;
  384. for (var n = _appended; n != null; n = n.Linked)
  385. {
  386. --index;
  387. array[index] = n.Item;
  388. }
  389. return array;
  390. }
  391. public override async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  392. {
  393. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  394. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  395. for (var n = _prepended; n != null; n = n.Linked)
  396. {
  397. list.Add(n.Item);
  398. }
  399. #if USE_AWAIT_FOREACH
  400. await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  401. {
  402. list.Add(item);
  403. }
  404. #else
  405. var en = _source.GetAsyncEnumerator(cancellationToken);
  406. try
  407. {
  408. while (await en.MoveNextAsync().ConfigureAwait(false))
  409. {
  410. list.Add(en.Current);
  411. }
  412. }
  413. finally
  414. {
  415. await en.DisposeAsync().ConfigureAwait(false);
  416. }
  417. #endif
  418. if (_appended != null)
  419. {
  420. using (var en2 = _appended.GetEnumerator(_appendCount))
  421. {
  422. while (en2.MoveNext())
  423. {
  424. list.Add(en2.Current);
  425. }
  426. }
  427. }
  428. return list;
  429. }
  430. public override async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  431. {
  432. if (_source is IAsyncIListProvider<TSource> listProv)
  433. {
  434. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  435. return count == -1 ? -1 : count + _appendCount + _prependCount;
  436. }
  437. return !onlyIfCheap || _source is ICollection<TSource> || _source is ICollection ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) + _appendCount + _prependCount : -1;
  438. }
  439. }
  440. }
  441. }