SkipLast.cs 3.3 KB

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