AppendPrepend.cs 17 KB

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