Cast.cs 2.6 KB

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