Reverse.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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;
  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. var temp = array[i];
  42. array[i] = array[j];
  43. array[j] = temp;
  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 ICollection<TSource>) && !(_source is 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. }
  100. }