ByteCircularBuffer.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. using System;
  2. namespace SWRIS.Models
  3. {
  4. public class ByteCircularBuffer
  5. {
  6. private byte[] _buffer;
  7. private int _head;
  8. private int _tail;
  9. private int _count;
  10. private readonly object _lock = new object();
  11. public ByteCircularBuffer(int capacity)
  12. {
  13. _buffer = new byte[capacity];
  14. }
  15. public int Length => _count;
  16. public void Write(byte[] data, int offset, int count)
  17. {
  18. lock (_lock)
  19. {
  20. if (_count + count > _buffer.Length)
  21. {
  22. // 自动扩容或丢弃旧数据
  23. EnsureCapacity(_count + count);
  24. }
  25. for (int i = 0; i < count; i++)
  26. {
  27. _buffer[_tail] = data[offset + i];
  28. _tail = (_tail + 1) % _buffer.Length;
  29. }
  30. _count += count;
  31. }
  32. }
  33. public int Read(byte[] data, int offset, int count)
  34. {
  35. lock (_lock)
  36. {
  37. int bytesToRead = Math.Min(count, _count);
  38. for (int i = 0; i < bytesToRead; i++)
  39. {
  40. data[offset + i] = _buffer[_head];
  41. _head = (_head + 1) % _buffer.Length;
  42. }
  43. _count -= bytesToRead;
  44. return bytesToRead;
  45. }
  46. }
  47. public int Peek(byte[] data, int offset, int count)
  48. {
  49. lock (_lock)
  50. {
  51. int bytesToPeek = Math.Min(count, _count);
  52. int tempHead = _head;
  53. for (int i = 0; i < bytesToPeek; i++)
  54. {
  55. data[offset + i] = _buffer[tempHead];
  56. tempHead = (tempHead + 1) % _buffer.Length;
  57. }
  58. return bytesToPeek;
  59. }
  60. }
  61. public byte PeekByte(int offset = 0)
  62. {
  63. lock (_lock)
  64. {
  65. if (offset >= _count) return 0;
  66. return _buffer[(_head + offset) % _buffer.Length];
  67. }
  68. }
  69. private void EnsureCapacity(int requiredCapacity)
  70. {
  71. if (requiredCapacity <= _buffer.Length) return;
  72. int newCapacity = Math.Max(_buffer.Length * 2, requiredCapacity);
  73. byte[] newBuffer = new byte[newCapacity];
  74. if (_head <= _tail)
  75. {
  76. Buffer.BlockCopy(_buffer, _head, newBuffer, 0, _count);
  77. }
  78. else
  79. {
  80. int firstPart = _buffer.Length - _head;
  81. Buffer.BlockCopy(_buffer, _head, newBuffer, 0, firstPart);
  82. Buffer.BlockCopy(_buffer, 0, newBuffer, firstPart, _tail);
  83. }
  84. _buffer = newBuffer;
  85. _head = 0;
  86. _tail = _count;
  87. }
  88. public void Clear()
  89. {
  90. lock (_lock)
  91. {
  92. _head = _tail = _count = 0;
  93. }
  94. }
  95. public void Remove(int count)
  96. {
  97. lock (_lock)
  98. {
  99. int bytesToRemove = Math.Min(count, _count);
  100. _head = (_head + bytesToRemove) % _buffer.Length;
  101. _count -= bytesToRemove;
  102. }
  103. }
  104. }
  105. }