Range.cs 2.9 KB

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