You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

FixedSizeQueue.cs 2.7 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace LLama.Common
  6. {
  7. /// <summary>
  8. /// A queue with fixed storage size.
  9. /// Currently it's only a naive implementation and needs to be further optimized in the future.
  10. /// </summary>
  11. public class FixedSizeQueue<T>
  12. : IEnumerable<T>
  13. {
  14. private readonly int _maxSize;
  15. private readonly List<T> _storage;
  16. public int Count => _storage.Count;
  17. public int Capacity => _maxSize;
  18. public FixedSizeQueue(int size)
  19. {
  20. _maxSize = size;
  21. _storage = new();
  22. }
  23. /// <summary>
  24. /// Fill the quene with the data. Please ensure that data.Count &lt;= size
  25. /// </summary>
  26. /// <param name="size"></param>
  27. /// <param name="data"></param>
  28. public FixedSizeQueue(int size, IEnumerable<T> data)
  29. {
  30. #if !NETSTANDARD2_0
  31. // Try to check the size without enumerating the entire IEnumerable. This may not be able to get the count,
  32. // in which case we'll have to check later
  33. if (data.TryGetNonEnumeratedCount(out var dataCount) && dataCount > size)
  34. throw new ArgumentException($"The max size set for the quene is {size}, but got {dataCount} initial values.");
  35. #endif
  36. // Size of "data" is unknown, copy it all into a list
  37. _maxSize = size;
  38. _storage = new List<T>(data);
  39. // Now check if that list is a valid size.
  40. if (_storage.Count > _maxSize)
  41. throw new ArgumentException($"The max size set for the quene is {size}, but got {_storage.Count} initial values.");
  42. }
  43. /// <summary>
  44. /// Replace every item in the queue with the given value
  45. /// </summary>
  46. /// <param name="value">The value to replace all items with</param>
  47. /// <returns>returns this</returns>
  48. public FixedSizeQueue<T> FillWith(T value)
  49. {
  50. for(var i = 0; i < Count; i++)
  51. {
  52. _storage[i] = value;
  53. }
  54. return this;
  55. }
  56. /// <summary>
  57. /// Enquene an element.
  58. /// </summary>
  59. /// <returns></returns>
  60. public void Enqueue(T item)
  61. {
  62. _storage.Add(item);
  63. if(_storage.Count >= _maxSize)
  64. {
  65. _storage.RemoveAt(0);
  66. }
  67. }
  68. /// <inheritdoc />
  69. public IEnumerator<T> GetEnumerator()
  70. {
  71. return _storage.GetEnumerator();
  72. }
  73. /// <inheritdoc />
  74. IEnumerator IEnumerable.GetEnumerator()
  75. {
  76. return GetEnumerator();
  77. }
  78. }
  79. }