RingBuffer.h 999 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 add(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. int getLength() const {
  21. return values;
  22. }
  23. bool canRemove() const {
  24. return values > 0;
  25. }
  26. bool remove() {
  27. if(values <= 0) {
  28. return true;
  29. }
  30. values--;
  31. readIndex = (readIndex + 1) % N;
  32. return false;
  33. }
  34. T& operator[](int index) {
  35. return data[(index + readIndex) % N];
  36. }
  37. const T& operator[](int index) const {
  38. return data[(index + readIndex) % N];
  39. }
  40. void clear() {
  41. writeIndex = 0;
  42. readIndex = 0;
  43. values = 0;
  44. }
  45. };
  46. #endif