Reverse.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  13. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.reverse?view=net-9.0-pp
  14. /// <summary>
  15. /// Inverts the order of the elements in a sequence.
  16. /// </summary>
  17. /// <typeparam name="TSource">The type of the elements of source.</typeparam>
  18. /// <param name="source">An async-enumerable sequence of values to reverse.</param>
  19. /// <returns>An async-enumerable sequence whose elements correspond to those of the input sequence in reverse order.</returns>
  20. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  21. public static IAsyncEnumerable<TSource> Reverse<TSource>(this IAsyncEnumerable<TSource> source)
  22. {
  23. if (source == null)
  24. throw Error.ArgumentNull(nameof(source));
  25. return new ReverseAsyncIterator<TSource>(source);
  26. }
  27. private sealed class ReverseAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  28. {
  29. private readonly IAsyncEnumerable<TSource> _source;
  30. private int _index;
  31. private TSource[]? _items;
  32. public ReverseAsyncIterator(IAsyncEnumerable<TSource> source)
  33. {
  34. _source = source;
  35. }
  36. public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  37. {
  38. var array = await _source.ToArrayAsync(cancellationToken).ConfigureAwait(false);
  39. // Array.Reverse() involves boxing for non-primitive value types, but
  40. // checking that has its own cost, so just use this approach for all types.
  41. for (int i = 0, j = array.Length - 1; i < j; ++i, --j)
  42. {
  43. (array[j], array[i]) = (array[i], array[j]);
  44. }
  45. return array;
  46. }
  47. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  48. {
  49. var list = await _source.ToListAsync(cancellationToken).ConfigureAwait(false);
  50. list.Reverse();
  51. return list;
  52. }
  53. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  54. {
  55. if (onlyIfCheap)
  56. {
  57. if (_source is IAsyncIListProvider<TSource> listProv)
  58. {
  59. return listProv.GetCountAsync(true, cancellationToken);
  60. }
  61. if (_source is not ICollection<TSource> && _source is not ICollection)
  62. {
  63. return new ValueTask<int>(-1);
  64. }
  65. }
  66. return _source.CountAsync(cancellationToken);
  67. }
  68. public override AsyncIteratorBase<TSource> Clone()
  69. {
  70. return new ReverseAsyncIterator<TSource>(_source);
  71. }
  72. public override async ValueTask DisposeAsync()
  73. {
  74. _items = null; // Just in case this ends up being long-lived, allow the memory to be reclaimed.
  75. await base.DisposeAsync().ConfigureAwait(false);
  76. }
  77. protected override async ValueTask<bool> MoveNextCore()
  78. {
  79. switch (_state)
  80. {
  81. case AsyncIteratorState.Allocated:
  82. _items = await _source.ToArrayAsync(_cancellationToken).ConfigureAwait(false);
  83. _index = _items.Length - 1;
  84. _state = AsyncIteratorState.Iterating;
  85. goto case AsyncIteratorState.Iterating;
  86. case AsyncIteratorState.Iterating:
  87. if (_index != -1)
  88. {
  89. _current = _items![_index];
  90. --_index;
  91. return true;
  92. }
  93. break;
  94. }
  95. await DisposeAsync().ConfigureAwait(false);
  96. return false;
  97. }
  98. }
  99. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  100. }
  101. }