80 lines
1.2 KiB
C++
80 lines
1.2 KiB
C++
#ifndef RINGBUFFER_H
|
|
#define RINGBUFFER_H
|
|
|
|
template <typename Scalar, int size> class RingBuffer {
|
|
|
|
private:
|
|
|
|
Scalar data[size];
|
|
|
|
volatile size_t head;
|
|
volatile size_t tail;
|
|
volatile size_t used;
|
|
|
|
public:
|
|
|
|
void init() {
|
|
head = 0;
|
|
tail = 0;
|
|
used = 0;
|
|
}
|
|
|
|
/** add one value to the buffer */
|
|
void addBlocking(const Scalar value) {
|
|
|
|
while (used == size) {os_delay_us(1000);}
|
|
|
|
data[head] = value;
|
|
head = (head + 1) % size;
|
|
++used;
|
|
}
|
|
|
|
/** add one value to the buffer */
|
|
void addIgnore(const Scalar value) {
|
|
|
|
if (used == size) {return;}
|
|
|
|
data[head] = value;
|
|
head = (head + 1) % size;
|
|
++used;
|
|
}
|
|
|
|
/** add multiple values to the buffer */
|
|
void add(const Scalar* value, const size_t len) {
|
|
for (size_t i = 0; i < len; ++i) {
|
|
add(value[i]);
|
|
}
|
|
}
|
|
|
|
/** anything available? */
|
|
bool hasNext() const {
|
|
return used != 0;
|
|
}
|
|
|
|
Scalar get() {
|
|
const Scalar res = data[tail];
|
|
tail = (tail + 1) % size;
|
|
--used;
|
|
return res;
|
|
}
|
|
|
|
const Scalar& getConst() {
|
|
const uint8_t idx = tail;
|
|
tail = (tail + 1) % size;
|
|
--used;
|
|
return data[idx];
|
|
}
|
|
|
|
// /** true if the buffer is currently empty */
|
|
// bool isEmpty() const {
|
|
// return head == tail;
|
|
// }
|
|
|
|
size_t getNumUsed() const {
|
|
return used;
|
|
}
|
|
|
|
};
|
|
|
|
#endif // RINGBUFFER_H
|