1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- #ifndef RINGBUFFER_H
- #define RINGBUFFER_H
- #include "data/Array.h"
- template<typename T, int N>
- class RingBuffer final {
- Array<T, N> data;
- int writeIndex = 0;
- int readIndex = 0;
- int values = 0;
- public:
- bool add(const T& t) {
- if(values >= N) {
- return true;
- }
- data[writeIndex] = t;
- writeIndex = (writeIndex + 1) % N;
- values++;
- return false;
- }
- int getLength() const {
- return values;
- }
- bool canRemove() const {
- return values > 0;
- }
- bool remove() {
- if(values <= 0) {
- return true;
- }
- values--;
- readIndex = (readIndex + 1) % N;
- return false;
- }
- T& operator[](int index) {
- return data[(index + readIndex) % N];
- }
- const T& operator[](int index) const {
- return data[(index + readIndex) % N];
- }
- void clear() {
- writeIndex = 0;
- readIndex = 0;
- values = 0;
- }
- };
- #endif
|