Skip to content

Instantly share code, notes, and snippets.

@adamski
Created June 17, 2016 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
};
@obb64
Copy link

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
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