TakeLast.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. /// <summary>
  13. /// Returns a specified number of contiguous elements from the end of an async-enumerable sequence.
  14. /// </summary>
  15. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  16. /// <param name="source">Source sequence.</param>
  17. /// <param name="count">Number of elements to take from the end of the source sequence.</param>
  18. /// <returns>An async-enumerable sequence containing the specified number of elements from the end of the source sequence.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  20. /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is less than zero.</exception>
  21. /// <remarks>
  22. /// This operator accumulates a buffer with a length enough to store elements <paramref name="count"/> elements. Upon completion of
  23. /// the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
  24. /// </remarks>
  25. public static IAsyncEnumerable<TSource> TakeLast<TSource>(this IAsyncEnumerable<TSource> source, int count)
  26. {
  27. if (source == null)
  28. throw Error.ArgumentNull(nameof(source));
  29. if (count <= 0)
  30. {
  31. return Empty<TSource>();
  32. }
  33. return Create(Core);
  34. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  35. {
  36. Queue<TSource> queue;
  37. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  38. {
  39. if (!await e.MoveNextAsync())
  40. {
  41. yield break;
  42. }
  43. queue = new Queue<TSource>();
  44. queue.Enqueue(e.Current);
  45. while (await e.MoveNextAsync())
  46. {
  47. if (queue.Count < count)
  48. {
  49. queue.Enqueue(e.Current);
  50. }
  51. else
  52. {
  53. do
  54. {
  55. queue.Dequeue();
  56. queue.Enqueue(e.Current);
  57. }
  58. while (await e.MoveNextAsync());
  59. break;
  60. }
  61. }
  62. }
  63. Debug.Assert(queue.Count <= count);
  64. do
  65. {
  66. yield return queue.Dequeue();
  67. }
  68. while (queue.Count > 0);
  69. }
  70. }
  71. }
  72. }