RingBuffer.h 735 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #ifndef RINGBUFFER_H
  2. #define RINGBUFFER_H
  3. #include "data/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. void clear() {
  30. writeIndex = 0;
  31. readIndex = 0;
  32. values = 0;
  33. }
  34. };
  35. #endif