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.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace LLama.Common
  7. {
  8. /// <summary>
  9. /// A queue with fixed storage size.
  10. /// Currently it's only a naive implementation and needs to be further optimized in the future.
  11. /// </summary>
  12. public class FixedSizeQueue<T>: IEnumerable<T>
  13. {
  14. int _maxSize;
  15. 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. // Try an early check on the amount of data supplied (if possible)
  31. if (data.TryGetNonEnumeratedCount(out var count) && count > size)
  32. throw new ArgumentException($"The max size set for the quene is {size}, but got {count} initial values.");
  33. // Size of "data" is unknown, copy it all into a list
  34. _maxSize = size;
  35. _storage = new List<T>(data);
  36. // Now check if that list is a valid size
  37. if (_storage.Count > _maxSize)
  38. throw new ArgumentException($"The max size set for the quene is {size}, but got {count} initial values.");
  39. }
  40. /// <summary>
  41. /// Replace every item in the queue with the given value
  42. /// </summary>
  43. /// <param name="value">The value to replace all items with</param>
  44. /// <returns>returns this</returns>
  45. public FixedSizeQueue<T> FillWith(T value)
  46. {
  47. for(int i = 0; i < Count; i++)
  48. {
  49. _storage[i] = value;
  50. }
  51. return this;
  52. }
  53. /// <summary>
  54. /// Enquene an element.
  55. /// </summary>
  56. /// <returns></returns>
  57. public void Enqueue(T item)
  58. {
  59. _storage.Add(item);
  60. if(_storage.Count >= _maxSize)
  61. {
  62. _storage.RemoveAt(0);
  63. }
  64. }
  65. public T[] ToArray()
  66. {
  67. return _storage.ToArray();
  68. }
  69. public IEnumerator<T> GetEnumerator()
  70. {
  71. return _storage.GetEnumerator();
  72. }
  73. IEnumerator IEnumerable.GetEnumerator()
  74. {
  75. return GetEnumerator();
  76. }
  77. }
  78. }