I have a fixed size circular buffer (implemented as an array): upon initialization, the buffer gets filled with the specified maximum number of elements which allows the use of a single position index in order to keep track of our current position in the circle.
What is an efficient way to access an element in the circular buffer? Here is my current solution:
int GetElement(int index)
{
if (index >= buffer_size || index < 0)
{
// some code to handle the case
}
else
{
// wrap the index
index = end_index + index >= buffer_size ? (index + end_index) - buffer_size : end_index + index;
}
return buffer[index];
}
Some definitions:
end_index
is the index of the element immediately after the last element in the circle (it would also be considered the same as the start_index, or the first element of the circle).
buffer_size
is the maximum size of the buffer.
Best I've come up with is:
public static int Wrap(int index, int n)
{
return ((index % n) + n) % n;
}
(Assuming you need to work with negative numbers)