CircularBuffer.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. // #define RESET_REMOVED_ELEMENTS
  2. namespace IngameDebugConsole
  3. {
  4. public class CircularBuffer<T>
  5. {
  6. private T[] arr;
  7. private int startIndex;
  8. public int Count { get; private set; }
  9. public T this[int index] { get { return arr[( startIndex + index ) % arr.Length]; } }
  10. public CircularBuffer( int capacity )
  11. {
  12. arr = new T[capacity];
  13. }
  14. // Old elements are overwritten when capacity is reached
  15. public void Add( T value )
  16. {
  17. if( Count < arr.Length )
  18. arr[Count++] = value;
  19. else
  20. {
  21. arr[startIndex] = value;
  22. if( ++startIndex >= arr.Length )
  23. startIndex = 0;
  24. }
  25. }
  26. }
  27. public class DynamicCircularBuffer<T>
  28. {
  29. private T[] arr;
  30. private int startIndex;
  31. public int Count { get; private set; }
  32. public T this[int index]
  33. {
  34. get { return arr[( startIndex + index ) % arr.Length]; }
  35. set { arr[( startIndex + index ) % arr.Length] = value; }
  36. }
  37. public DynamicCircularBuffer( int initialCapacity = 2 )
  38. {
  39. arr = new T[initialCapacity];
  40. }
  41. public void Add( T value )
  42. {
  43. if( Count >= arr.Length )
  44. {
  45. int prevSize = arr.Length;
  46. int newSize = prevSize > 0 ? prevSize * 2 : 2; // Size must be doubled (at least), or the shift operation below must consider IndexOutOfRange situations
  47. System.Array.Resize( ref arr, newSize );
  48. if( startIndex > 0 )
  49. {
  50. if( startIndex <= ( prevSize - 1 ) / 2 )
  51. {
  52. // Move elements [0,startIndex) to the end
  53. for( int i = 0; i < startIndex; i++ )
  54. {
  55. arr[i + prevSize] = arr[i];
  56. #if RESET_REMOVED_ELEMENTS
  57. arr[i] = default( T );
  58. #endif
  59. }
  60. }
  61. else
  62. {
  63. // Move elements [startIndex,prevSize) to the end
  64. int delta = newSize - prevSize;
  65. for( int i = prevSize - 1; i >= startIndex; i-- )
  66. {
  67. arr[i + delta] = arr[i];
  68. #if RESET_REMOVED_ELEMENTS
  69. arr[i] = default( T );
  70. #endif
  71. }
  72. startIndex += delta;
  73. }
  74. }
  75. }
  76. this[Count++] = value;
  77. }
  78. public T RemoveFirst()
  79. {
  80. T element = arr[startIndex];
  81. #if RESET_REMOVED_ELEMENTS
  82. arr[startIndex] = default( T );
  83. #endif
  84. if( ++startIndex >= arr.Length )
  85. startIndex = 0;
  86. Count--;
  87. return element;
  88. }
  89. public T RemoveLast()
  90. {
  91. T element = arr[Count - 1];
  92. #if RESET_REMOVED_ELEMENTS
  93. arr[Count - 1] = default( T );
  94. #endif
  95. Count--;
  96. return element;
  97. }
  98. }
  99. }