Created
June 17, 2016 21:15
-
-
Save adamski/0136e690ab3384eeca730f735c5ab2c8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
}; |
Thanks for spotting that! I'll test and update accordingly. The code could also be improved by using memcpy
in getSnapshot
instead of the for
loop. I still haven't gotten around to that!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello Adam
in push:
If bufferSize is 256 and head is 255:
buffer[head++] = value;
// sets value to element 255 and increase head to 256in getSnapshot:
head and readIndex will be 256
readBuffer[i] = buffer[readIndex];
// read element 256 which is outside the buffer !Could this solve the problem:
Regards, Oliver