AppendPrepend.cs 18 KB

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