Skip to content

Instantly share code, notes, and snippets.

@adamski
Created June 17, 2016 21:15
Show Gist options
  • Save adamski/0136e690ab3384eeca730f735c5ab2c8 to your computer and use it in GitHub Desktop.
Save adamski/0136e690ab3384eeca730f735c5ab2c8 to your computer and use it in GitHub Desktop.
/**
* 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;
};
@adamski
Copy link
Author

adamski commented Jan 1, 2020

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