Cast.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. public static IAsyncEnumerable<TResult> Cast<TResult>(this IAsyncEnumerable<object> source)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. // Check to see if it already is and short-circuit
  16. if (source is IAsyncEnumerable<TResult> typedSource)
  17. {
  18. return typedSource;
  19. }
  20. return new CastAsyncIterator<TResult>(source);
  21. }
  22. internal sealed class CastAsyncIterator<TResult> : AsyncIterator<TResult>
  23. {
  24. private readonly IAsyncEnumerable<object> _source;
  25. private IAsyncEnumerator<object> _enumerator;
  26. public CastAsyncIterator(IAsyncEnumerable<object> source)
  27. {
  28. Debug.Assert(source != null);
  29. _source = source;
  30. }
  31. public override AsyncIteratorBase<TResult> Clone()
  32. {
  33. return new CastAsyncIterator<TResult>(_source);
  34. }
  35. public override async ValueTask DisposeAsync()
  36. {
  37. if (_enumerator != null)
  38. {
  39. await _enumerator.DisposeAsync().ConfigureAwait(false);
  40. _enumerator = null;
  41. }
  42. await base.DisposeAsync().ConfigureAwait(false);
  43. }
  44. protected override async ValueTask<bool> MoveNextCore()
  45. {
  46. switch (_state)
  47. {
  48. case AsyncIteratorState.Allocated:
  49. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  50. _state = AsyncIteratorState.Iterating;
  51. goto case AsyncIteratorState.Iterating;
  52. case AsyncIteratorState.Iterating:
  53. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  54. {
  55. _current = (TResult)_enumerator.Current;
  56. return true;
  57. }
  58. await DisposeAsync().ConfigureAwait(false);
  59. break;
  60. }
  61. return false;
  62. }
  63. }
  64. }
  65. }