AppendPrepend.cs 18 KB

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