Reverse.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. /// <summary>
  13. /// Inverts the order of the elements in a sequence.
  14. /// </summary>
  15. /// <typeparam name="TSource">The type of the elements of source.</typeparam>
  16. /// <param name="source">An async-enumerable sequence of values to reverse.</param>
  17. /// <returns>An async-enumerable sequence whose elements correspond to those of the input sequence in reverse order.</returns>
  18. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  19. public static IAsyncEnumerable<TSource> Reverse<TSource>(this IAsyncEnumerable<TSource> source)
  20. {
  21. if (source == null)
  22. throw Error.ArgumentNull(nameof(source));
  23. return new ReverseAsyncIterator<TSource>(source);
  24. }
  25. private sealed class ReverseAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  26. {
  27. private readonly IAsyncEnumerable<TSource> _source;
  28. private int _index;
  29. private TSource[]? _items;
  30. public ReverseAsyncIterator(IAsyncEnumerable<TSource> source)
  31. {
  32. _source = source;
  33. }
  34. public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  35. {
  36. var array = await _source.ToArrayAsync(cancellationToken).ConfigureAwait(false);
  37. // Array.Reverse() involves boxing for non-primitive value types, but
  38. // checking that has its own cost, so just use this approach for all types.
  39. for (int i = 0, j = array.Length - 1; i < j; ++i, --j)
  40. {
  41. (array[j], array[i]) = (array[i], array[j]);
  42. }
  43. return array;
  44. }
  45. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  46. {
  47. var list = await _source.ToListAsync(cancellationToken).ConfigureAwait(false);
  48. list.Reverse();
  49. return list;
  50. }
  51. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  52. {
  53. if (onlyIfCheap)
  54. {
  55. if (_source is IAsyncIListProvider<TSource> listProv)
  56. {
  57. return listProv.GetCountAsync(true, cancellationToken);
  58. }
  59. if (_source is not ICollection<TSource> && _source is not ICollection)
  60. {
  61. return new ValueTask<int>(-1);
  62. }
  63. }
  64. return _source.CountAsync(cancellationToken);
  65. }
  66. public override AsyncIteratorBase<TSource> Clone()
  67. {
  68. return new ReverseAsyncIterator<TSource>(_source);
  69. }
  70. public override async ValueTask DisposeAsync()
  71. {
  72. _items = null; // Just in case this ends up being long-lived, allow the memory to be reclaimed.
  73. await base.DisposeAsync().ConfigureAwait(false);
  74. }
  75. protected override async ValueTask<bool> MoveNextCore()
  76. {
  77. switch (_state)
  78. {
  79. case AsyncIteratorState.Allocated:
  80. _items = await _source.ToArrayAsync(_cancellationToken).ConfigureAwait(false);
  81. _index = _items.Length - 1;
  82. _state = AsyncIteratorState.Iterating;
  83. goto case AsyncIteratorState.Iterating;
  84. case AsyncIteratorState.Iterating:
  85. if (_index != -1)
  86. {
  87. _current = _items![_index];
  88. --_index;
  89. return true;
  90. }
  91. break;
  92. }
  93. await DisposeAsync().ConfigureAwait(false);
  94. return false;
  95. }
  96. }
  97. }
  98. }