71 lines
977 B
C++
71 lines
977 B
C++
#ifndef DOUBLEBUFFER_H
|
|
#define DOUBLEBUFFER_H
|
|
|
|
template <typename Scalar, int size> class DoubleBuffer {
|
|
|
|
private:
|
|
|
|
Scalar data[size*2];
|
|
Scalar* ptr1;
|
|
Scalar* ptr2;
|
|
|
|
volatile uint32_t head;
|
|
volatile bool _needsFlush;
|
|
|
|
public:
|
|
|
|
void init() {
|
|
ptr1 = &data[0];
|
|
ptr2 = &data[size];
|
|
head = 0;
|
|
_needsFlush = false;
|
|
}
|
|
|
|
/** add new values to buffer A. swaps A and B if A is full */
|
|
void add(const Scalar value) {
|
|
|
|
ptr1[head] = value; // ptr1
|
|
++head;
|
|
|
|
if (head >= size) {
|
|
head = 0;
|
|
swap();
|
|
_needsFlush = true;
|
|
}
|
|
|
|
}
|
|
|
|
/** get data from buffer B */
|
|
const Scalar* getData() const {
|
|
return ptr2;
|
|
}
|
|
|
|
/** true if the buffer is currently empty */
|
|
bool isEmpty() const {
|
|
return head == 0;
|
|
}
|
|
|
|
bool needsFlush() const {
|
|
return _needsFlush;
|
|
}
|
|
|
|
void markFlushed() {
|
|
_needsFlush = false;
|
|
}
|
|
|
|
uint32_t getSize() const {
|
|
return size;
|
|
}
|
|
|
|
private:
|
|
|
|
void swap() {
|
|
Scalar* tmp = ptr1;
|
|
ptr1 = ptr2;
|
|
ptr2 = tmp;
|
|
}
|
|
|
|
};
|
|
|
|
#endif // DOUBLEBUFFER_H
|