Range.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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.Generic;
  5. using System.Diagnostics;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<int> Range(int start, int count)
  13. {
  14. if (count < 0)
  15. throw new ArgumentOutOfRangeException(nameof(count));
  16. if (count == 0)
  17. return Empty<int>();
  18. return new RangeAsyncIterator(start, count);
  19. }
  20. private sealed class RangeAsyncIterator : AsyncIterator<int>, IAsyncIListProvider<int>
  21. {
  22. private readonly int start;
  23. private readonly int end;
  24. public RangeAsyncIterator(int start, int count)
  25. {
  26. Debug.Assert(count > 0);
  27. this.start = start;
  28. this.end = start + count;
  29. }
  30. public override AsyncIterator<int> Clone() => new RangeAsyncIterator(start, end - start);
  31. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken) => Task.FromResult(end - start);
  32. public Task<int[]> ToArrayAsync(CancellationToken cancellationToken)
  33. {
  34. var res = new int[end - start];
  35. var value = start;
  36. for (var i = 0; i < res.Length; i++)
  37. {
  38. res[i] = value++;
  39. }
  40. return Task.FromResult(res);
  41. }
  42. public Task<List<int>> ToListAsync(CancellationToken cancellationToken)
  43. {
  44. var res = new List<int>(end - start);
  45. for (var value = start; value < end; value++)
  46. {
  47. res.Add(value);
  48. }
  49. return Task.FromResult(res);
  50. }
  51. protected override async Task<bool> MoveNextCore()
  52. {
  53. switch (state)
  54. {
  55. case AsyncIteratorState.Allocated:
  56. current = start;
  57. state = AsyncIteratorState.Iterating;
  58. return true;
  59. case AsyncIteratorState.Iterating:
  60. current++;
  61. if (current != end)
  62. {
  63. return true;
  64. }
  65. break;
  66. }
  67. await DisposeAsync().ConfigureAwait(false);
  68. return false;
  69. }
  70. }
  71. }
  72. }