RingBuffer.h 644 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #ifndef RINGBUFFER_H
  2. #define RINGBUFFER_H
  3. #include "utils/Array.h"
  4. template<typename T, int N>
  5. class RingBuffer final {
  6. Array<T, N> data;
  7. int writeIndex = 0;
  8. int readIndex = 0;
  9. int values = 0;
  10. public:
  11. bool write(const T& t) {
  12. if(values >= N) {
  13. return true;
  14. }
  15. data[writeIndex] = t;
  16. writeIndex = (writeIndex + 1) % N;
  17. values++;
  18. return false;
  19. }
  20. bool canRead() const {
  21. return values > 0;
  22. }
  23. T read() {
  24. values -= values > 0;
  25. T& t = data[readIndex];
  26. readIndex = (readIndex + 1) % N;
  27. return t;
  28. }
  29. };
  30. #endif