SkipLast.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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<TSource> SkipLast<TSource>(this IAsyncEnumerable<TSource> source, int count)
  13. {
  14. if (source == null)
  15. throw Error.ArgumentNull(nameof(source));
  16. if (count <= 0)
  17. {
  18. // Return source if not actually skipping, but only if it's a type from here, to avoid
  19. // issues if collections are used as keys or otherwise must not be aliased.
  20. if (source is AsyncIterator<TSource>)
  21. {
  22. return source;
  23. }
  24. count = 0;
  25. }
  26. return new SkipLastAsyncIterator<TSource>(source, count);
  27. }
  28. private sealed class SkipLastAsyncIterator<TSource> : AsyncIterator<TSource>
  29. {
  30. private readonly int _count;
  31. private readonly IAsyncEnumerable<TSource> _source;
  32. private IAsyncEnumerator<TSource> _enumerator;
  33. private Queue<TSource> _queue;
  34. public SkipLastAsyncIterator(IAsyncEnumerable<TSource> source, int count)
  35. {
  36. Debug.Assert(source != null);
  37. _source = source;
  38. _count = count;
  39. }
  40. public override AsyncIterator<TSource> Clone()
  41. {
  42. return new SkipLastAsyncIterator<TSource>(_source, _count);
  43. }
  44. public override async ValueTask DisposeAsync()
  45. {
  46. if (_enumerator != null)
  47. {
  48. await _enumerator.DisposeAsync().ConfigureAwait(false);
  49. _enumerator = null;
  50. }
  51. _queue = null; // release the memory
  52. await base.DisposeAsync().ConfigureAwait(false);
  53. }
  54. protected override async ValueTask<bool> MoveNextCore(CancellationToken cancellationToken)
  55. {
  56. switch (state)
  57. {
  58. case AsyncIteratorState.Allocated:
  59. _enumerator = _source.GetAsyncEnumerator(cancellationToken);
  60. _queue = new Queue<TSource>();
  61. state = AsyncIteratorState.Iterating;
  62. goto case AsyncIteratorState.Iterating;
  63. case AsyncIteratorState.Iterating:
  64. while (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  65. {
  66. var item = _enumerator.Current;
  67. _queue.Enqueue(item);
  68. if (_queue.Count > _count)
  69. {
  70. current = _queue.Dequeue();
  71. return true;
  72. }
  73. }
  74. break;
  75. }
  76. await DisposeAsync().ConfigureAwait(false);
  77. return false;
  78. }
  79. }
  80. }
  81. }