OfType.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Cysharp.Threading.Tasks.Internal;
  2. using System;
  3. using System.Threading;
  4. namespace Cysharp.Threading.Tasks.Linq
  5. {
  6. public static partial class UniTaskAsyncEnumerable
  7. {
  8. public static IUniTaskAsyncEnumerable<TResult> OfType<TResult>(this IUniTaskAsyncEnumerable<Object> source)
  9. {
  10. Error.ThrowArgumentNullException(source, nameof(source));
  11. return new OfType<TResult>(source);
  12. }
  13. }
  14. internal sealed class OfType<TResult> : IUniTaskAsyncEnumerable<TResult>
  15. {
  16. readonly IUniTaskAsyncEnumerable<object> source;
  17. public OfType(IUniTaskAsyncEnumerable<object> source)
  18. {
  19. this.source = source;
  20. }
  21. public IUniTaskAsyncEnumerator<TResult> GetAsyncEnumerator(CancellationToken cancellationToken = default)
  22. {
  23. return new _OfType(source, cancellationToken);
  24. }
  25. class _OfType : AsyncEnumeratorBase<object, TResult>
  26. {
  27. public _OfType(IUniTaskAsyncEnumerable<object> source, CancellationToken cancellationToken)
  28. : base(source, cancellationToken)
  29. {
  30. }
  31. protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result)
  32. {
  33. if (sourceHasCurrent)
  34. {
  35. if (SourceCurrent is TResult castCurent)
  36. {
  37. Current = castCurent;
  38. result = true;
  39. return true;
  40. }
  41. else
  42. {
  43. result = default;
  44. return false;
  45. }
  46. }
  47. result = false;
  48. return true;
  49. }
  50. }
  51. }
  52. }