Repeat.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Cysharp.Threading.Tasks.Internal;
  2. using System.Threading;
  3. namespace Cysharp.Threading.Tasks.Linq
  4. {
  5. public static partial class UniTaskAsyncEnumerable
  6. {
  7. public static IUniTaskAsyncEnumerable<TElement> Repeat<TElement>(TElement element, int count)
  8. {
  9. if (count < 0) throw Error.ArgumentOutOfRange(nameof(count));
  10. return new Repeat<TElement>(element, count);
  11. }
  12. }
  13. internal class Repeat<TElement> : IUniTaskAsyncEnumerable<TElement>
  14. {
  15. readonly TElement element;
  16. readonly int count;
  17. public Repeat(TElement element, int count)
  18. {
  19. this.element = element;
  20. this.count = count;
  21. }
  22. public IUniTaskAsyncEnumerator<TElement> GetAsyncEnumerator(CancellationToken cancellationToken = default)
  23. {
  24. return new _Repeat(element, count, cancellationToken);
  25. }
  26. class _Repeat : IUniTaskAsyncEnumerator<TElement>
  27. {
  28. readonly TElement element;
  29. readonly int count;
  30. int remaining;
  31. CancellationToken cancellationToken;
  32. public _Repeat(TElement element, int count, CancellationToken cancellationToken)
  33. {
  34. this.element = element;
  35. this.count = count;
  36. this.cancellationToken = cancellationToken;
  37. this.remaining = count;
  38. }
  39. public TElement Current => element;
  40. public UniTask<bool> MoveNextAsync()
  41. {
  42. cancellationToken.ThrowIfCancellationRequested();
  43. if (remaining-- != 0)
  44. {
  45. return CompletedTasks.True;
  46. }
  47. return CompletedTasks.False;
  48. }
  49. public UniTask DisposeAsync()
  50. {
  51. return default;
  52. }
  53. }
  54. }
  55. }