AppendPrepend.cs 18 KB

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