CircularBuffer.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "CircularBuffer.h"
  2. using namespace bell;
  3. CircularBuffer::CircularBuffer(size_t dataCapacity)
  4. {
  5. this->dataCapacity = dataCapacity;
  6. buffer = std::vector<uint8_t>(dataCapacity);
  7. this->dataSemaphore = std::make_unique<bell::WrappedSemaphore>(5);
  8. };
  9. size_t CircularBuffer::write(const uint8_t *data, size_t bytes)
  10. {
  11. if (bytes == 0)
  12. return 0;
  13. std::lock_guard<std::mutex> guard(bufferMutex);
  14. size_t bytesToWrite = std::min(bytes, dataCapacity - dataSize);
  15. // Write in a single step
  16. if (bytesToWrite <= dataCapacity - endIndex)
  17. {
  18. memcpy(buffer.data() + endIndex, data, bytesToWrite);
  19. endIndex += bytesToWrite;
  20. if (endIndex == dataCapacity)
  21. endIndex = 0;
  22. }
  23. // Write in two steps
  24. else {
  25. size_t firstChunkSize = dataCapacity - endIndex;
  26. memcpy(buffer.data() + endIndex, data, firstChunkSize);
  27. size_t secondChunkSize = bytesToWrite - firstChunkSize;
  28. memcpy(buffer.data(), data + firstChunkSize, secondChunkSize);
  29. endIndex = secondChunkSize;
  30. }
  31. dataSize += bytesToWrite;
  32. // this->dataSemaphore->give();
  33. return bytesToWrite;
  34. }
  35. void CircularBuffer::emptyBuffer() {
  36. std::lock_guard<std::mutex> guard(bufferMutex);
  37. begIndex = 0;
  38. dataSize = 0;
  39. endIndex = 0;
  40. }
  41. void CircularBuffer::emptyExcept(size_t sizeToSet) {
  42. std::lock_guard<std::mutex> guard(bufferMutex);
  43. if (sizeToSet > dataSize)
  44. sizeToSet = dataSize;
  45. dataSize = sizeToSet;
  46. endIndex = begIndex + sizeToSet;
  47. if (endIndex > dataCapacity) {
  48. endIndex -= dataCapacity;
  49. }
  50. }
  51. size_t CircularBuffer::read(uint8_t *data, size_t bytes)
  52. {
  53. if (bytes == 0)
  54. return 0;
  55. std::lock_guard<std::mutex> guard(bufferMutex);
  56. size_t bytesToRead = std::min(bytes, dataSize);
  57. // Read in a single step
  58. if (bytesToRead <= dataCapacity - begIndex)
  59. {
  60. memcpy(data, buffer.data() + begIndex, bytesToRead);
  61. begIndex += bytesToRead;
  62. if (begIndex == dataCapacity)
  63. begIndex = 0;
  64. }
  65. // Read in two steps
  66. else
  67. {
  68. size_t firstChunkSize = dataCapacity - begIndex;
  69. memcpy(data, buffer.data() + begIndex, firstChunkSize);
  70. size_t secondChunkSize = bytesToRead - firstChunkSize;
  71. memcpy(data + firstChunkSize, buffer.data(), secondChunkSize);
  72. begIndex = secondChunkSize;
  73. }
  74. dataSize -= bytesToRead;
  75. return bytesToRead;
  76. }