Skip to content

Instantly share code, notes, and snippets.

@adamski

adamski/RingBuffer.h

Created Jun 17, 2016
Embed
What would you like to do?
/**
* 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;
};
@obb64

This comment has been minimized.

Copy link

@obb64 obb64 commented Dec 30, 2019

Hello Adam
in push:
If bufferSize is 256 and head is 255:
buffer[head++] = value; // sets value to element 255 and increase head to 256

in getSnapshot:
head and readIndex will be 256
readBuffer[i] = buffer[readIndex]; // read element 256 which is outside the buffer !

Could this solve the problem:

void push (float value)
    {
        if (count < bufferSize && head == 0)  {
            buffer[count++] = value;
        }     else if (count >= bufferSize) {
            buffer[head++] = value;
            if (head >= bufferSize) {
                head = 0;
            }
        }
    }

Regards, Oliver

@adamski

This comment has been minimized.

Copy link
Owner Author

@adamski 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
You can’t perform that action at this time.