RingBuffer.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. namespace Universal;
  2. public class RingBuffer<T>(int size)
  3. {
  4. private readonly T[] _BufferArea = new T[size];
  5. private readonly int max = size - 1;
  6. int _startIndex = 0;
  7. int _endIndex = 0;
  8. bool _full = false;
  9. public void Insert(T content)
  10. {
  11. lock (this)
  12. {
  13. _BufferArea[_endIndex] = content;
  14. _endIndex = _endIndex == max ? 0 : _endIndex + 1;
  15. if (_endIndex == _startIndex)
  16. {
  17. _full = true;
  18. _startIndex = _startIndex == max ? 0 : _startIndex + 1;
  19. }
  20. }
  21. }
  22. private int LastStartIndex
  23. {
  24. get
  25. {
  26. if (!_full)
  27. return 0;
  28. if (_startIndex == 0)
  29. return max;
  30. return _startIndex - 1;
  31. }
  32. }
  33. private int LastEndIndex
  34. {
  35. get
  36. {
  37. if (_endIndex == 0)
  38. return max;
  39. return _endIndex - 1;
  40. }
  41. }
  42. public T[] ReadValues()
  43. {
  44. if (!_full)
  45. return _BufferArea[0.._endIndex];
  46. if (LastEndIndex > LastStartIndex)
  47. return _BufferArea;
  48. List<T> result = [];
  49. result.AddRange(_BufferArea[(LastEndIndex + 1)..]);
  50. result.AddRange(_BufferArea[0..LastStartIndex]);
  51. return [.. result];
  52. }
  53. public void Clear()
  54. {
  55. lock (this)
  56. {
  57. this._startIndex = 0;
  58. this._endIndex = 0;
  59. this._full = false;
  60. }
  61. }
  62. }