RingBuffer.cs 1.6 KB

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