Generate.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  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<TResult> Generate<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  14. {
  15. if (condition == null)
  16. throw new ArgumentNullException(nameof(condition));
  17. if (iterate == null)
  18. throw new ArgumentNullException(nameof(iterate));
  19. if (resultSelector == null)
  20. throw new ArgumentNullException(nameof(resultSelector));
  21. return new GenerateAsyncIterator<TState, TResult>(initialState, condition, iterate, resultSelector);
  22. }
  23. private sealed class GenerateAsyncIterator<TState, TResult> : AsyncIterator<TResult>
  24. {
  25. private readonly Func<TState, bool> condition;
  26. private readonly TState initialState;
  27. private readonly Func<TState, TState> iterate;
  28. private readonly Func<TState, TResult> resultSelector;
  29. private TState currentState;
  30. private bool started;
  31. public GenerateAsyncIterator(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  32. {
  33. this.initialState = initialState;
  34. this.condition = condition;
  35. this.iterate = iterate;
  36. this.resultSelector = resultSelector;
  37. }
  38. public override AsyncIterator<TResult> Clone()
  39. {
  40. return new GenerateAsyncIterator<TState, TResult>(initialState, condition, iterate, resultSelector);
  41. }
  42. public override void Dispose()
  43. {
  44. currentState = default(TState);
  45. base.Dispose();
  46. }
  47. protected override Task<bool> MoveNextCore(CancellationToken cancellationToken)
  48. {
  49. switch (state)
  50. {
  51. case AsyncIteratorState.Allocated:
  52. started = false;
  53. currentState = initialState;
  54. state = AsyncIteratorState.Iterating;
  55. goto case AsyncIteratorState.Iterating;
  56. case AsyncIteratorState.Iterating:
  57. if (started)
  58. {
  59. currentState = iterate(currentState);
  60. }
  61. started = true;
  62. if (condition(currentState))
  63. {
  64. current = resultSelector(currentState);
  65. return TaskExt.True;
  66. }
  67. break;
  68. }
  69. Dispose();
  70. return TaskExt.False;
  71. }
  72. }
  73. }
  74. }