Created
June 17, 2016 21:15
-
-
Save adamski/0136e690ab3384eeca730f735c5ab2c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple ring buffer which is always the same length | |
* for keeping a stream of float input values | |
* Designed to give a snapshot in time | |
* | |
* TODO: use vector queue to store values instead of array pointer | |
*/ | |
class RingBuffer | |
{ | |
public: | |
RingBuffer (int bufferSize) : bufferSize (bufferSize), count (0), head (0), buffer (nullptr), readBuffer (nullptr) | |
{ | |
buffer = new float[bufferSize]; | |
readBuffer = new float[bufferSize]; | |
} | |
~RingBuffer() | |
{ | |
delete buffer; | |
delete readBuffer; | |
} | |
void push (float value) | |
{ | |
if (count < bufferSize && head == 0) | |
{ | |
buffer[count++] = value; | |
} | |
else if (count >= bufferSize) | |
{ | |
if (head >= bufferSize) | |
{ | |
head = 0; | |
} | |
buffer[head++] = value; | |
} | |
} | |
/** | |
* Return a snapshot of the buffer as a continous array | |
*/ | |
const float* getSnapshot () | |
{ | |
// Set up read buffer as continuous stream | |
int readIndex = head; | |
for (int i = 0; i < count; i++) | |
{ | |
readBuffer[i] = buffer[readIndex]; | |
readIndex = (readIndex + 1) % bufferSize; | |
} | |
return readBuffer; | |
} | |
private: | |
int bufferSize, head, count; | |
float* buffer; | |
float* readBuffer; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for spotting that! I'll test and update accordingly. The code could also be improved by using
memcpy
ingetSnapshot
instead of thefor
loop. I still haven't gotten around to that!