SkipLast.cs 3.2 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 new ArgumentNullException(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 AsyncIterator<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. this.source = source;
  37. this.count = count;
  38. }
  39. public override AsyncIterator<TSource> Clone()
  40. {
  41. return new SkipLastAsyncIterator<TSource>(source, count);
  42. }
  43. public override async Task 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 Task<bool> MoveNextCore()
  54. {
  55. switch (state)
  56. {
  57. case AsyncIteratorState.Allocated:
  58. enumerator = source.GetAsyncEnumerator();
  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. }