Ring Buffer¶
The Ring Buffer is a very interesting data structure that works very similar to an array, except that its capacity is capped and iterating over its elements will automatically jump from its tail to its head when reaching the end of the list. Think of it as an array with a limited capacity where the tail joins the head, thus shaping it a ring.
To create a ring buffer, create a class that inherits from the Ring<T>
class or directly use the Ring<T>
type. For example, to create a ring buffer with 5 elements:
Ring<string> myRing = new Ring<string>(
"string 1",
"string 2",
"string 3",
"string 4",
"string 5",
);
The ring buffer starts with its index pointing to the first element. Calling Next()
, Current()
and Previous()
will change the pointer and return the new value. For example:
// Set the index to 0:
myRing.Index = 0;
// Iterate 100 times:
for (int i = 0; i < 100; ++i)
{
// Print the next value:
Debug.Log(myRing.Next());
}
The previous code snippet will iterate the previous ring 20 times (100 / 5) and print the name of each entry.
An interesting method of the ring buffer is the Update(callback)
. This method accepts a method as its parameter and executes it for every element of the ring. For example:
myRing.Update(Debug.Log);
The previous method will print each of the entries of the ring buffer, as the Debug.Log()
method is applied to each one of them.