AsyncEnumerablePartition.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. // Copied from https://github.com/dotnet/corefx/blob/5f1dd8298e4355b63bb760d88d437a91b3ca808c/src/System.Linq/src/System/Linq/Partition.cs
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. /// <summary>
  12. /// An iterator that yields the items of part of an <see cref="IAsyncEnumerable{TSource}"/>.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the source enumerable.</typeparam>
  15. internal sealed class AsyncEnumerablePartition<TSource> : AsyncIterator<TSource>, IAsyncPartition<TSource>
  16. {
  17. private readonly IAsyncEnumerable<TSource> _source;
  18. private readonly int _minIndexInclusive;
  19. private readonly int _maxIndexInclusive; // -1 if we want everything past _minIndexInclusive.
  20. // If this is -1, it's impossible to set a limit on the count.
  21. private IAsyncEnumerator<TSource> _enumerator;
  22. internal AsyncEnumerablePartition(IAsyncEnumerable<TSource> source, int minIndexInclusive, int maxIndexInclusive)
  23. {
  24. Debug.Assert(source != null);
  25. Debug.Assert(!(source is IList<TSource>), $"The caller needs to check for {nameof(IList<TSource>)}.");
  26. Debug.Assert(minIndexInclusive >= 0);
  27. Debug.Assert(maxIndexInclusive >= -1);
  28. // Note that although maxIndexInclusive can't grow, it can still be int.MaxValue.
  29. // We support partitioning enumerables with > 2B elements. For example, e.Skip(1).Take(int.MaxValue) should work.
  30. // But if it is int.MaxValue, then minIndexInclusive must != 0. Otherwise, our count may overflow.
  31. Debug.Assert(maxIndexInclusive == -1 || (maxIndexInclusive - minIndexInclusive < int.MaxValue), $"{nameof(Limit)} will overflow!");
  32. Debug.Assert(maxIndexInclusive == -1 || minIndexInclusive <= maxIndexInclusive);
  33. _source = source;
  34. _minIndexInclusive = minIndexInclusive;
  35. _maxIndexInclusive = maxIndexInclusive;
  36. }
  37. // If this is true (e.g. at least one Take call was made), then we have an upper bound
  38. // on how many elements we can have.
  39. private bool HasLimit => _maxIndexInclusive != -1;
  40. private int Limit => (_maxIndexInclusive + 1) - _minIndexInclusive; // This is that upper bound.
  41. public override AsyncIteratorBase<TSource> Clone()
  42. {
  43. return new AsyncEnumerablePartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive);
  44. }
  45. public override async ValueTask DisposeAsync()
  46. {
  47. if (_enumerator != null)
  48. {
  49. await _enumerator.DisposeAsync().ConfigureAwait(false);
  50. _enumerator = null;
  51. }
  52. await base.DisposeAsync().ConfigureAwait(false);
  53. }
  54. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  55. {
  56. if (onlyIfCheap)
  57. {
  58. return new ValueTask<int>(-1);
  59. }
  60. return Core();
  61. async ValueTask<int> Core()
  62. {
  63. if (!HasLimit)
  64. {
  65. // If HasLimit is false, we contain everything past _minIndexInclusive.
  66. // Therefore, we have to iterate the whole enumerable.
  67. return Math.Max(await _source.CountAsync(cancellationToken).ConfigureAwait(false) - _minIndexInclusive, 0);
  68. }
  69. var en = _source.GetAsyncEnumerator(cancellationToken);
  70. try
  71. {
  72. // We only want to iterate up to _maxIndexInclusive + 1.
  73. // Past that, we know the enumerable will be able to fit this partition,
  74. // so the count will just be _maxIndexInclusive + 1 - _minIndexInclusive.
  75. // Note that it is possible for _maxIndexInclusive to be int.MaxValue here,
  76. // so + 1 may result in signed integer overflow. We need to handle this.
  77. // At the same time, however, we are guaranteed that our max count can fit
  78. // in an int because if that is true, then _minIndexInclusive must > 0.
  79. var count = await SkipAndCountAsync((uint)_maxIndexInclusive + 1, en).ConfigureAwait(false);
  80. Debug.Assert(count != (uint)int.MaxValue + 1 || _minIndexInclusive > 0, "Our return value will be incorrect.");
  81. return Math.Max((int)count - _minIndexInclusive, 0);
  82. }
  83. finally
  84. {
  85. await en.DisposeAsync().ConfigureAwait(false);
  86. }
  87. }
  88. }
  89. private bool _hasSkipped;
  90. private int _taken;
  91. protected override async ValueTask<bool> MoveNextCore()
  92. {
  93. switch (_state)
  94. {
  95. case AsyncIteratorState.Allocated:
  96. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  97. _hasSkipped = false;
  98. _taken = 0;
  99. _state = AsyncIteratorState.Iterating;
  100. goto case AsyncIteratorState.Iterating;
  101. case AsyncIteratorState.Iterating:
  102. if (!_hasSkipped)
  103. {
  104. if (!await SkipBeforeFirstAsync(_enumerator).ConfigureAwait(false))
  105. {
  106. // Reached the end before we finished skipping.
  107. break;
  108. }
  109. _hasSkipped = true;
  110. }
  111. if ((!HasLimit || _taken < Limit) && await _enumerator.MoveNextAsync().ConfigureAwait(false))
  112. {
  113. if (HasLimit)
  114. {
  115. // If we are taking an unknown number of elements, it's important not to increment _state.
  116. // _state - 3 may eventually end up overflowing & we'll hit the Dispose branch even though
  117. // we haven't finished enumerating.
  118. _taken++;
  119. }
  120. _current = _enumerator.Current;
  121. return true;
  122. }
  123. break;
  124. }
  125. await DisposeAsync().ConfigureAwait(false);
  126. return false;
  127. }
  128. #if NOTYET
  129. public override IAsyncEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector)
  130. {
  131. return new SelectIPartitionIterator<TSource, TResult>(this, selector);
  132. }
  133. public override IAsyncEnumerable<TResult> Select<TResult>(Func<TSource, ValueTask<TResult>> selector)
  134. {
  135. return new SelectIPartitionIterator<TSource, TResult>(this, selector);
  136. }
  137. #endif
  138. public IAsyncPartition<TSource> Skip(int count)
  139. {
  140. var minIndex = _minIndexInclusive + count;
  141. if (!HasLimit)
  142. {
  143. if (minIndex < 0)
  144. {
  145. // If we don't know our max count and minIndex can no longer fit in a positive int,
  146. // then we will need to wrap ourselves in another iterator.
  147. // This can happen, for example, during e.Skip(int.MaxValue).Skip(int.MaxValue).
  148. return new AsyncEnumerablePartition<TSource>(this, count, -1);
  149. }
  150. }
  151. else if ((uint)minIndex > (uint)_maxIndexInclusive)
  152. {
  153. // If minIndex overflows and we have an upper bound, we will go down this branch.
  154. // We know our upper bound must be smaller than minIndex, since our upper bound fits in an int.
  155. // This branch should not be taken if we don't have a bound.
  156. return AsyncEnumerable.EmptyAsyncIterator<TSource>.Instance;
  157. }
  158. Debug.Assert(minIndex >= 0, $"We should have taken care of all cases when {nameof(minIndex)} overflows.");
  159. return new AsyncEnumerablePartition<TSource>(_source, minIndex, _maxIndexInclusive);
  160. }
  161. public IAsyncPartition<TSource> Take(int count)
  162. {
  163. var maxIndex = _minIndexInclusive + count - 1;
  164. if (!HasLimit)
  165. {
  166. if (maxIndex < 0)
  167. {
  168. // If we don't know our max count and maxIndex can no longer fit in a positive int,
  169. // then we will need to wrap ourselves in another iterator.
  170. // Note that although maxIndex may be too large, the difference between it and
  171. // _minIndexInclusive (which is count - 1) must fit in an int.
  172. // Example: e.Skip(50).Take(int.MaxValue).
  173. return new AsyncEnumerablePartition<TSource>(this, 0, count - 1);
  174. }
  175. }
  176. else if ((uint)maxIndex >= (uint)_maxIndexInclusive)
  177. {
  178. // If we don't know our max count, we can't go down this branch.
  179. // It's always possible for us to contain more than count items, as the rest
  180. // of the enumerable past _minIndexInclusive can be arbitrarily long.
  181. return this;
  182. }
  183. Debug.Assert(maxIndex >= 0, $"We should have taken care of all cases when {nameof(maxIndex)} overflows.");
  184. return new AsyncEnumerablePartition<TSource>(_source, _minIndexInclusive, maxIndex);
  185. }
  186. public async ValueTask<Maybe<TSource>> TryGetElementAtAsync(int index, CancellationToken cancellationToken)
  187. {
  188. // If the index is negative or >= our max count, return early.
  189. if (index >= 0 && (!HasLimit || index < Limit))
  190. {
  191. var en = _source.GetAsyncEnumerator(cancellationToken);
  192. try
  193. {
  194. Debug.Assert(_minIndexInclusive + index >= 0, $"Adding {nameof(index)} caused {nameof(_minIndexInclusive)} to overflow.");
  195. if (await SkipBeforeAsync(_minIndexInclusive + index, en).ConfigureAwait(false) && await en.MoveNextAsync().ConfigureAwait(false))
  196. {
  197. return new Maybe<TSource>(en.Current);
  198. }
  199. }
  200. finally
  201. {
  202. await en.DisposeAsync().ConfigureAwait(false);
  203. }
  204. }
  205. return new Maybe<TSource>();
  206. }
  207. public async ValueTask<Maybe<TSource>> TryGetFirstAsync(CancellationToken cancellationToken)
  208. {
  209. var en = _source.GetAsyncEnumerator(cancellationToken);
  210. try
  211. {
  212. if (await SkipBeforeFirstAsync(en).ConfigureAwait(false) && await en.MoveNextAsync().ConfigureAwait(false))
  213. {
  214. return new Maybe<TSource>(en.Current);
  215. }
  216. }
  217. finally
  218. {
  219. await en.DisposeAsync().ConfigureAwait(false);
  220. }
  221. return new Maybe<TSource>();
  222. }
  223. public async ValueTask<Maybe<TSource>> TryGetLastAsync(CancellationToken cancellationToken)
  224. {
  225. var en = _source.GetAsyncEnumerator(cancellationToken);
  226. try
  227. {
  228. if (await SkipBeforeFirstAsync(en).ConfigureAwait(false) && await en.MoveNextAsync().ConfigureAwait(false))
  229. {
  230. var remaining = Limit - 1; // Max number of items left, not counting the current element.
  231. var comparand = HasLimit ? 0 : int.MinValue; // If we don't have an upper bound, have the comparison always return true.
  232. TSource result;
  233. do
  234. {
  235. remaining--;
  236. result = en.Current;
  237. }
  238. while (remaining >= comparand && await en.MoveNextAsync().ConfigureAwait(false));
  239. return new Maybe<TSource>(result);
  240. }
  241. }
  242. finally
  243. {
  244. await en.DisposeAsync().ConfigureAwait(false);
  245. }
  246. return new Maybe<TSource>();
  247. }
  248. public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  249. {
  250. var en = _source.GetAsyncEnumerator(cancellationToken);
  251. try
  252. {
  253. if (await SkipBeforeFirstAsync(en).ConfigureAwait(false) && await en.MoveNextAsync().ConfigureAwait(false))
  254. {
  255. var remaining = Limit - 1; // Max number of items left, not counting the current element.
  256. var comparand = HasLimit ? 0 : int.MinValue; // If we don't have an upper bound, have the comparison always return true.
  257. var maxCapacity = HasLimit ? Limit : int.MaxValue;
  258. var builder = new List<TSource>(maxCapacity);
  259. do
  260. {
  261. remaining--;
  262. builder.Add(en.Current);
  263. }
  264. while (remaining >= comparand && await en.MoveNextAsync().ConfigureAwait(false));
  265. return builder.ToArray();
  266. }
  267. }
  268. finally
  269. {
  270. await en.DisposeAsync().ConfigureAwait(false);
  271. }
  272. #if NO_ARRAY_EMPTY
  273. return EmptyArray<TSource>.Value;
  274. #else
  275. return Array.Empty<TSource>();
  276. #endif
  277. }
  278. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  279. {
  280. var list = new List<TSource>();
  281. var en = _source.GetAsyncEnumerator(cancellationToken);
  282. try
  283. {
  284. if (await SkipBeforeFirstAsync(en).ConfigureAwait(false) && await en.MoveNextAsync().ConfigureAwait(false))
  285. {
  286. var remaining = Limit - 1; // Max number of items left, not counting the current element.
  287. var comparand = HasLimit ? 0 : int.MinValue; // If we don't have an upper bound, have the comparison always return true.
  288. do
  289. {
  290. remaining--;
  291. list.Add(en.Current);
  292. }
  293. while (remaining >= comparand && await en.MoveNextAsync().ConfigureAwait(false));
  294. }
  295. }
  296. finally
  297. {
  298. await en.DisposeAsync().ConfigureAwait(false);
  299. }
  300. return list;
  301. }
  302. private ValueTask<bool> SkipBeforeFirstAsync(IAsyncEnumerator<TSource> en) => SkipBeforeAsync(_minIndexInclusive, en);
  303. private static async ValueTask<bool> SkipBeforeAsync(int index, IAsyncEnumerator<TSource> en)
  304. {
  305. var n = await SkipAndCountAsync(index, en).ConfigureAwait(false);
  306. return n == index;
  307. }
  308. private static async ValueTask<int> SkipAndCountAsync(int index, IAsyncEnumerator<TSource> en)
  309. {
  310. Debug.Assert(index >= 0);
  311. return (int)await SkipAndCountAsync((uint)index, en).ConfigureAwait(false);
  312. }
  313. private static async ValueTask<uint> SkipAndCountAsync(uint index, IAsyncEnumerator<TSource> en)
  314. {
  315. Debug.Assert(en != null);
  316. for (uint i = 0; i < index; i++)
  317. {
  318. if (!await en.MoveNextAsync().ConfigureAwait(false))
  319. {
  320. return i;
  321. }
  322. }
  323. return index;
  324. }
  325. }
  326. }