AppendPrepend.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. _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 ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken);
  72. public abstract ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken);
  73. public abstract ValueTask<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 ValueTask<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. cancellationToken.ThrowIfCancellationRequested();
  156. var array = new TSource[count];
  157. int index;
  158. if (_appending)
  159. {
  160. index = 0;
  161. }
  162. else
  163. {
  164. array[0] = _item;
  165. index = 1;
  166. }
  167. if (_source is ICollection<TSource> sourceCollection)
  168. {
  169. sourceCollection.CopyTo(array, index);
  170. }
  171. else
  172. {
  173. await foreach (var item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  174. {
  175. array[index] = item;
  176. ++index;
  177. }
  178. }
  179. if (_appending)
  180. {
  181. array[array.Length - 1] = _item;
  182. }
  183. return array;
  184. }
  185. public override async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  186. {
  187. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  188. cancellationToken.ThrowIfCancellationRequested();
  189. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  190. if (!_appending)
  191. {
  192. list.Add(_item);
  193. }
  194. await foreach (var item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  195. {
  196. list.Add(item);
  197. }
  198. if (_appending)
  199. {
  200. list.Add(_item);
  201. }
  202. return list;
  203. }
  204. public override async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  205. {
  206. if (_source is IAsyncIListProvider<TSource> listProv)
  207. {
  208. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  209. return count == -1 ? -1 : count + 1;
  210. }
  211. return !onlyIfCheap || _source is ICollection<TSource> || _source is ICollection ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) + 1 : -1;
  212. }
  213. }
  214. private sealed class AppendPrependNAsyncIterator<TSource> : AppendPrependAsyncIterator<TSource>
  215. {
  216. private readonly SingleLinkedNode<TSource>? _prepended;
  217. private readonly SingleLinkedNode<TSource>? _appended;
  218. private readonly int _prependCount;
  219. private readonly int _appendCount;
  220. private SingleLinkedNode<TSource>? _node;
  221. private int _mode;
  222. private IEnumerator<TSource>? _appendedEnumerator;
  223. public AppendPrependNAsyncIterator(IAsyncEnumerable<TSource> source, SingleLinkedNode<TSource>? prepended, SingleLinkedNode<TSource>? appended, int prependCount, int appendCount)
  224. : base(source)
  225. {
  226. Debug.Assert(prepended != null || appended != null);
  227. Debug.Assert(prependCount > 0 || appendCount > 0);
  228. Debug.Assert(prependCount + appendCount >= 2);
  229. Debug.Assert((prepended?.GetCount() ?? 0) == prependCount);
  230. Debug.Assert((appended?.GetCount() ?? 0) == appendCount);
  231. _prepended = prepended;
  232. _appended = appended;
  233. _prependCount = prependCount;
  234. _appendCount = appendCount;
  235. }
  236. public override AsyncIteratorBase<TSource> Clone()
  237. {
  238. return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, _appended, _prependCount, _appendCount);
  239. }
  240. public override async ValueTask DisposeAsync()
  241. {
  242. if (_appendedEnumerator != null)
  243. {
  244. _appendedEnumerator.Dispose();
  245. _appendedEnumerator = null;
  246. }
  247. await base.DisposeAsync().ConfigureAwait(false);
  248. }
  249. protected override async ValueTask<bool> MoveNextCore()
  250. {
  251. switch (_state)
  252. {
  253. case AsyncIteratorState.Allocated:
  254. _mode = 1;
  255. _state = AsyncIteratorState.Iterating;
  256. goto case AsyncIteratorState.Iterating;
  257. case AsyncIteratorState.Iterating:
  258. switch (_mode)
  259. {
  260. case 1:
  261. _node = _prepended;
  262. _mode = 2;
  263. goto case 2;
  264. case 2:
  265. if (_node != null)
  266. {
  267. _current = _node.Item;
  268. _node = _node.Linked;
  269. return true;
  270. }
  271. GetSourceEnumerator(_cancellationToken);
  272. _mode = 3;
  273. goto case 3;
  274. case 3:
  275. if (await LoadFromEnumeratorAsync().ConfigureAwait(false))
  276. {
  277. return true;
  278. }
  279. if (_appended != null)
  280. {
  281. _appendedEnumerator = _appended.GetEnumerator(_appendCount);
  282. _mode = 4;
  283. goto case 4;
  284. }
  285. break;
  286. case 4:
  287. if (_appendedEnumerator!.MoveNext())
  288. {
  289. _current = _appendedEnumerator.Current;
  290. return true;
  291. }
  292. break;
  293. }
  294. break;
  295. }
  296. await DisposeAsync().ConfigureAwait(false);
  297. return false;
  298. }
  299. public override AppendPrependAsyncIterator<TSource> Append(TSource item)
  300. {
  301. var res = _appended != null ? _appended.Add(item) : new SingleLinkedNode<TSource>(item);
  302. return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, res, _prependCount, _appendCount + 1);
  303. }
  304. public override AppendPrependAsyncIterator<TSource> Prepend(TSource item)
  305. {
  306. var res = _prepended != null ? _prepended.Add(item) : new SingleLinkedNode<TSource>(item);
  307. return new AppendPrependNAsyncIterator<TSource>(_source, res, _appended, _prependCount + 1, _appendCount);
  308. }
  309. public override async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  310. {
  311. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  312. if (count == -1)
  313. {
  314. return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(false);
  315. }
  316. var array = new TSource[count];
  317. var index = 0;
  318. for (var n = _prepended; n != null; n = n.Linked)
  319. {
  320. array[index] = n.Item;
  321. ++index;
  322. }
  323. if (_source is ICollection<TSource> sourceCollection)
  324. {
  325. sourceCollection.CopyTo(array, index);
  326. }
  327. else
  328. {
  329. await foreach (var item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  330. {
  331. array[index] = item;
  332. ++index;
  333. }
  334. }
  335. index = array.Length;
  336. for (var n = _appended; n != null; n = n.Linked)
  337. {
  338. --index;
  339. array[index] = n.Item;
  340. }
  341. return array;
  342. }
  343. public override async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  344. {
  345. var count = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  346. var list = count == -1 ? new List<TSource>() : new List<TSource>(count);
  347. for (var n = _prepended; n != null; n = n.Linked)
  348. {
  349. list.Add(n.Item);
  350. }
  351. await foreach (var item in _source.WithCancellation(cancellationToken).ConfigureAwait(false))
  352. {
  353. list.Add(item);
  354. }
  355. if (_appended != null)
  356. {
  357. using var en2 = _appended.GetEnumerator(_appendCount);
  358. while (en2.MoveNext())
  359. {
  360. list.Add(en2.Current);
  361. }
  362. }
  363. return list;
  364. }
  365. public override async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  366. {
  367. if (_source is IAsyncIListProvider<TSource> listProv)
  368. {
  369. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  370. return count == -1 ? -1 : count + _appendCount + _prependCount;
  371. }
  372. return !onlyIfCheap || _source is ICollection<TSource> || _source is ICollection ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) + _appendCount + _prependCount : -1;
  373. }
  374. }
  375. }
  376. }