Circular Buffering
Circular Buffering
Circular Buffering
Circular Buffer
• A circular buffer is a data structure
consisting of three parts:
• A fixed-length buffer/array.
• A head index.
• A tail index.
• The general purpose of a Circular
Buffer is to receive a stream of data
(usually arbitrarily long or infinite) but
to only house a finite amount of it in memory at any time.
01/04/2023 2
Circular Buffer
• The primary mechanism for the Circular Buffer is to treat a normal
buffer as if the next element after the last space in the buffer is going
to be the first element of the buffer.
01/04/2023 3
Circular Buffer
• As you can see, the data rolls around the end of the buffer, back to the
beginning.
• Head indicates the beginning of stored data, where we have the stalest
element.
• Tail indicates the location immediately after stored data, where the freshest
element will go.
• In this case, the nine from our last example is the freshest element.
01/04/2023 5
Circular Buffer
• When the buffer is full, both Tail and Head point to the same element
in the underlying buffer.
• This means that if we want to accept new data (let's say 10) into the
buffer, we need to replace the oldest data (3) with the newest data (10).
• Again, replacing old data with new data may need to wait until the old
data is used, depending on the application.
01/04/2023 6
Circular Buffer
• When removing the oldest element, the head index moves over to the
next element.
• When adding an element, the tail index moves over to the next
element.
01/04/2023 7
Circular Buffer
• When the buffer is full and you still add an element, the stalest element is
over written and both head and tail are moved over to the next element.
• The tail space in the buffer is at 4, with the last, stalest element at 3.
01/04/2023 9
Circular Buffer – Indexing
• We need to find a way to associate the following circular buffer
indexes with the underlying actual indexes.
i
return array[i];
void push(char x) {
array[tail] = x;
} else {
count++;
01/04/2023 12