﻿

# Circular buffer  A ring showing, conceptually, a circular buffer. This visually shows that the buffer has no real end and it can loop around the buffer. However, since memory is never physically created as a ring, a linear representation is generally used as is done below.

A circular buffer, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams.

## Uses

An example that could possibly use an overwriting circular buffer is with multimedia. If the buffer is used as the bounded buffer in the producer-consumer problem then it is probably desired for the producer (e.g., an audio generator) to overwrite old data if the consumer (e.g., the sound card) is unable to momentarily keep up. Another example is the digital waveguide synthesis method which uses circular buffers to efficiently simulate the sound of vibrating strings or wind instruments.

The "prized" attribute of a circular buffer is that it does not need to have its elements shuffled around when one is consumed. (If a non-circular buffer were used then it would be necessary to shift all elements when one is consumed.) In other words, the circular buffer is well suited as a FIFO buffer while a standard, non-circular buffer is well suited as a LIFO buffer.

Circular buffering makes a good implementation strategy for a Queue that has fixed maximum size. Should a maximum size be adopted for a queue, then a circular buffer is a completely ideal implementation; all queue operations are constant time. However, expanding a circular buffer requires shifting memory, which is comparatively costly. For arbitrarily expanding queues, a Linked list approach may be preferred instead.

## How it works

A circular buffer first starts empty and of some predefined length. For example, this is a 7-element buffer: Assume that a 1 is written into the middle of the buffer (exact starting location does not matter in a circular buffer): Then assume that two more elements are added — 2 & 3 — which get appended after the 1: If two elements are then removed from the buffer, the oldest values inside the buffer are removed. The two elements removed, in this case, are 1 & 2 leaving the buffer with just a 3: If the buffer has 7 elements then it is completely full: A consequence of the circular buffer is that when it is full and a subsequent write is performed, then it starts overwriting the oldest data. In this case, two more elements — A & B — are added and they overwrite the 3 & 4: Alternatively, the routines that manage the buffer could prevent overwriting the data and return an error or raise an exception. Whether or not data is overwritten is up to the semantics of the buffer routines or the application using the circular buffer.

Finally, if two elements are now removed then what would be returned is not 3 & 4 but 5 & 6 because A & B overwrote the 3 & the 4 yielding the buffer with: ## Circular buffer mechanics

What is not shown in the example above is the mechanics of how the circular buffer is managed.

### Start / End Pointers

Generally, a circular buffer requires three pointers:

• one to the actual buffer in memory
• one to point to the start of valid data
• one to point to the end of valid data

Alternatively, a fixed-length buffer with two integers to keep track of indices can be used in languages that do not have pointers.

Taking a couple of examples from above. (While there are numerous ways to label the pointers and exact semantics can vary, this is one way to do it.)

This image shows a partially-full buffer: This image shows a full buffer with two elements having been overwritten: What to note about the second one is that after each element is overwritten then the start pointer is incremented as well.

## Difficulties

### Full / Empty Buffer Distinction

A small disadvantage of relying on pointers or relative indices of the start and end of data is, that in the case the buffer is entirely full, both pointers point to the same element: This is exactly the same situation as when the buffer is empty: To solve this confusion there are a number of solutions:

#### Always Keep One Slot Open

This simple solution always keeps one slot unallocated. A full buffer has at most (size − 1) slots. If both pointers are pointing at the same location, the buffer is empty. If the end (write) pointer, plus one, equals the start (read) pointer, then the buffer is full.

• Very simple and robust.
• You need only the two pointers.

• You can never use the entire buffer.
• You might only be able to access one element at a time, since you won't easily know how many elements are next to each other in memory.[clarification needed].

An example implementation in C: (Keep One Slot Open)

```#include <stdio.h>
#include <string.h>
#include <malloc.h>

/*!
* Circular Buffer Example (Keep one slot open)
* Compile: gcc cbuf.c -o cbuf.exe
*/

/**< Buffer Size */
#define BUFFER_SIZE    10
#define NUM_OF_ELEMS   (BUFFER_SIZE-1)

/**< Circular Buffer Types */
typedef unsigned char INT8U;
typedef INT8U KeyType;
typedef struct
{
INT8U writePointer; /**< write pointer */
INT8U size;         /**< size of circular buffer */
KeyType keys;    /**< Element of circular buffer */
} CircularBuffer;

/**< Init Circular Buffer */
CircularBuffer* CircularBufferInit(CircularBuffer** pQue, int size)
{
int sz = size*sizeof(KeyType)+sizeof(CircularBuffer);
*pQue = (CircularBuffer*) malloc(sz);
if(*pQue)
{
printf("Init CircularBuffer: keys[%d] (%d)\n", size, sz);
(*pQue)->size=size;
(*pQue)->writePointer = 0;
}
return *pQue;
}

inline int CircularBufferIsFull(CircularBuffer* que)
{
return (((que->writePointer + 1) % que->size) == que->readPointer);
}

inline int CircularBufferIsEmpty(CircularBuffer* que)
{
}

inline int CircularBufferEnque(CircularBuffer* que, KeyType k)
{
int isFull = CircularBufferIsFull(que);
if(!isFull)
{
que->keys[que->writePointer] = k;
que->writePointer++;
que->writePointer %= que->size;
}
return isFull;
}

inline int CircularBufferDeque(CircularBuffer* que, KeyType* pK)
{
int isEmpty =  CircularBufferIsEmpty(que);
if(!isEmpty)
{
}
return(isEmpty);
}

inline int CircularBufferPrint(CircularBuffer* que)
{
int i=0;
int isEmpty =  CircularBufferIsEmpty(que);
int isFull  =  CircularBufferIsFull(que);
printf("\n==Q: w:%d r:%d f:%d e:%d\n",
for(i=0; i< que->size; i++)
{
printf("%d ", que->keys[i]);
}
printf("\n");
return(isEmpty);
}

int main(int argc, char *argv[])
{
CircularBuffer* que;
KeyType a = 101;
int isEmpty, i;

CircularBufferInit(&que, BUFFER_SIZE);
CircularBufferPrint(que);

for(i=1; i<=3; i++)
{
a=10*i;
printf("\n\n===\nTest: Insert %d-%d\n", a, a+NUM_OF_ELEMS-1);
while(! CircularBufferEnque(que, a++));

//CircularBufferPrint(que);
printf("\nRX%d:", i);
a=0;
isEmpty = CircularBufferDeque(que, &a);
while (!isEmpty)
{
printf("%02d ", a);
a=0;
isEmpty = CircularBufferDeque(que, &a);
}
//CircularBufferPrint(que);
}

free(que);
return 0;
}
```

An example implementation in C: (Use all slots) (but is dangerous - an attempt to insert items on a full queue will yield success, but will, in fact, overwrite the queue)

```#include <stdio.h>
#include <string.h>
#include <malloc.h>

/*!
* Circular Buffer Example
* Compile: gcc cbuf.c -o cbuf.exe
*/

/**< Buffer Size */
#define BUFFER_SIZE  16

/**< Circular Buffer Types */
typedef unsigned char INT8U;
typedef INT8U KeyType;
typedef struct
{
INT8U writePointer; /**< write pointer */
INT8U size;         /**< size of circular buffer */
KeyType keys;    /**< Element of circular buffer */
} CircularBuffer;

/**< Init Circular Buffer */
CircularBuffer* CircularBufferInit(CircularBuffer** pQue, int size)
{
int sz = size*sizeof(KeyType)+sizeof(CircularBuffer);
*pQue = (CircularBuffer*) malloc(sz);
if(*pQue)
{
printf("Init CircularBuffer: keys[%d] (%d)\n", size, sz);
(*pQue)->size=size;
(*pQue)->writePointer = 0;
}
return *pQue;
}

inline int CircularBufferIsFull(CircularBuffer* que)
{
return ((que->writePointer + 1) % que->size == que->readPointer);
}

inline int CircularBufferIsEmpty(CircularBuffer* que)
{
}

inline int CircularBufferEnque(CircularBuffer* que, KeyType k)
{
int isFull = CircularBufferIsFull(que);
que->keys[que->writePointer] = k;
que->writePointer++;
que->writePointer %= que->size;
return isFull;
}

inline int CircularBufferDeque(CircularBuffer* que, KeyType* pK)
{
int isEmpty =  CircularBufferIsEmpty(que);
return(isEmpty);
}

int main(int argc, char *argv[])
{
CircularBuffer* que;
KeyType a = 0;
int isEmpty;
CircularBufferInit(&que, BUFFER_SIZE);

while(! CircularBufferEnque(que, a++));

do {
isEmpty = CircularBufferDeque(que, &a);
printf("%02d ", a);
} while (!isEmpty);
printf("\n");
free(que);
return 0;
}
```

#### Use a Fill Count

The second simplest solution is to use a fill count. The fill count is implemented as an additional variable which keeps the number of readable items in the buffer. This variable has to be increased if the write (end) pointer is moved, and to be decreased if the read (start) pointer is moved.

In the situation if both pointers pointing at the same location, you consider the fill count to distinguish if the buffer is empty or full.

• Simple.
• Needs only one additional variable.

• You need to keep track of a third variable. This can require complex logic, especially if you are working with different threads.

Alternately, you can replace the second pointer with the fill count and generate the second pointer as required by incrementing the first pointer by the fill count, modulo buffer size.

• Simple.

Another solution is to keep counts of the number of items written to and read from the circular buffer. Both counts are stored in signed integer variables with numerical limits larger than the number of items that can be stored and are allowed to wrap freely.

The unsigned difference (write_count - read_count) always yields the number of items placed in the buffer and not yet retrieved. This can indicate that the buffer is empty, partially full, completely full (without waste of a storage location) or in a state of overrun.

• The source and sink of data can implement independent policies for dealing with a full buffer and overrun while adhering to the rule that only the source of data modifies the write count and only the sink of data modifies the read count. This can result in elegant and robust circular buffer implementations even in multi-threaded environments.

• You need two additional variables.

#### Record last operation

Another solution is to keep a flag indicating whether the most recent operation was a read or a write. If the two pointers are equal, then the flag will show whether the buffer is full or empty: if the most recent operation was a write, the buffer must be full, and conversely if it was a read, it must be empty.

• Only a single bit needs to be stored (which may be particularly useful if the algorithm is implemented in hardware)
• The test for full/empty is simple

• You need an extra variable

#### Absolute indices

If indices are used instead of pointers, indices can store read/write counts instead of the offset from start of the buffer. This is similar to the above solution, except that there are no separate variables, and relative indices are obtained on the fly by division modulo the buffer's length.

• No extra variables are needed.

• Every access needs an additional modulo operation.
• If counter wrap is possible, complex logic can be needed if the buffer's length is not a divisor of the counter's capacity.

On binary computers, both of these disadvantages disappear if the buffer's length is a power of two—at the cost of a constraint on possible buffers lengths.

A little bit more complex are multiple read pointers on the same circular buffer. This is useful if you have n threads, which are reading from the same buffer, but one thread writing to the buffer.

### Chunked Buffer

Much more complex are different chunks of data in the same circular buffer. The writer is not only writing elements to the buffer, it also assigns these elements to chunks[citation needed].

The reader should not only be able to read from the buffer, it should also get informed about the chunk borders.

Example: The writer is reading data from small files, writing them into the same circular buffer. The reader is reading the data, but needs to know when and which file is starting at a given position.

## Optimization

A circular-buffer implementation may be optimized by mapping the underlying buffer to two contiguous regions of virtual memory. (Naturally, the underlying buffer‘s length must then equal some multiple of the system’s page size.) Reading from and writing to the circular buffer may then be carried out with greater efficiency by means of direct memory access; those accesses which fall beyond the end of the first virtual-memory region will automatically wrap around to the beginning of the underlying buffer. When the read offset is advanced into the second virtual-memory region, both offsets—read and write—are decremented by the length of the underlying buffer.

### Optimized POSIX Implementation

```#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>

#define report_exceptional_condition() abort ()

struct ring_buffer
{

unsigned long count_bytes;
unsigned long write_offset_bytes;
};

//Warning order should be at least 12 for Linux
void
ring_buffer_create (struct ring_buffer *buffer, unsigned long order)
{
char path[] = "/dev/shm/ring-buffer-XXXXXX";
int file_descriptor;
int status;

file_descriptor = mkstemp (path);
if (file_descriptor < 0)
report_exceptional_condition ();

if (status)
report_exceptional_condition ();

buffer->count_bytes = 1UL << order;
buffer->write_offset_bytes = 0;

status = ftruncate (file_descriptor, buffer->count_bytes);
if (status)
report_exceptional_condition ();

buffer->address = mmap (NULL, buffer->count_bytes << 1, PROT_NONE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);

report_exceptional_condition ();

MAP_FIXED | MAP_SHARED, file_descriptor, 0);

report_exceptional_condition ();

MAP_FIXED | MAP_SHARED, file_descriptor, 0);

report_exceptional_condition ();

status = close (file_descriptor);
if (status)
report_exceptional_condition ();
}

void
ring_buffer_free (struct ring_buffer *buffer)
{
int status;

status = munmap (buffer->address, buffer->count_bytes << 1);
if (status)
report_exceptional_condition ();
}

void *
{
/*** void pointer arithmetic is a constraint violation. ***/
}

void
unsigned long count_bytes)
{
buffer->write_offset_bytes += count_bytes;
}

void *
{
}

void
unsigned long count_bytes)
{

{
buffer->write_offset_bytes -= buffer->count_bytes;
}
}

unsigned long
ring_buffer_count_bytes (struct ring_buffer *buffer)
{
}

unsigned long
ring_buffer_count_free_bytes (struct ring_buffer *buffer)
{
return buffer->count_bytes - ring_buffer_count_bytes (buffer);
}

void
ring_buffer_clear (struct ring_buffer *buffer)
{
buffer->write_offset_bytes = 0;
}
```
```//---------------------------------------------------------------------------
// template class Queue
//---------------------------------------------------------------------------
template <class T> class Queue {

T *qbuf;   // buffer data
int qsize; //
int head;  // index begin data
int tail;  // index stop data

inline void Free()
{
if (qbuf != 0)
{
delete []qbuf;
qbuf= 0;
}
qsize= 1;
}

public:
Queue()
{
qsize= 32;
qbuf= new T[qsize];
}

Queue(const int size): qsize(1), qbuf(0), head(0), tail(0)
{
if ((size <= 0) || (size & (size - 1)))
{
throw "Value is not power of two";
}

qsize= size;
qbuf= new T[qsize];
}

~Queue()
{
Free();
}

void Enqueue(const T &p)
{
if (IsFull())
{
throw "Queue is full";
}

qbuf[tail]= p;
tail= (tail + 1) & (qsize - 1);
}

// Retrieve the item from the queue
void Dequeue(T &p)
{
if (IsEmpty())
{
throw "Queue is empty";
}

}

// Get i-element with not delete
void Peek(const int i, T &p) const
{
int j= 0;
while (k != tail)
{
if (j == i) break;
j++;

k= (k + 1) & (qsize - 1);
}
if (k == tail) throw "Out of range";
p= qbuf[k];
}

// Size must by: 1, 2, 4, 8, 16, 32, 64, ..
void Resize(const int size)
{
if ((size <= 0) || (size & (size - 1)))
{
throw "Value is not power of two";
}

Free();
qsize= size;
qbuf= new T[qsize];
}

inline void Clear(void) { head= tail= 0; }

inline int  GetCapacity(void) const { return (qsize - 1); }

// Count elements
inline int  GetBusy(void) const   { return ((head > tail) ? qsize : 0) + tail - head; }

// true - if queue if empty
inline bool IsEmpty(void) const { return (head == tail); }

// true - if queue if full
inline bool IsFull(void) const  { return ( ((tail + 1) & (qsize - 1)) == head ); }

};
//---------------------------------------------------------------------------
// Use:
Queue <int> Q;
Q.Enqueue(5);
Q.Enqueue(100);
Q.Enqueue(13);
int len= Q.GetBusy();
int val;
Q.Dequeue(val);

//---------------------------------------------------------------------------
```

Wikimedia Foundation. 2010.

### Look at other dictionaries:

• Circular — is a basic geometric shape such as a Circle. Contents 1 Documents 2 Travel and transportation 3 Places …   Wikipedia

• Buffer circulaire — Un cercle représentant un buffer circulaire de manière conceptuelle. En réalité, une représentation linéaire est utilisée, et la partie orange est simplement écrasée. Un buffer circulaire est une structure de données utilisant un buffer de taille …   Wikipédia en Français

• Circular dichroism — (CD) refers to the differential absorption of left and right circularly polarized light. This phenomenon was discovered by Jean Baptiste Biot, Augustin Fresnel, and Aimé Cotton in the first half of the 19th century. It is exhibited in… …   Wikipedia

• Circular saw — This miter saw uses a circular saw mounted to cut at an angle Buzzsaw redirects here. For other uses, see Buzzsaw (disambiguation). The circular saw is a machine using a toothed metal cutting disc or blade. The term is also loosely used for the… …   Wikipedia

• buffer —    An area of memory set aside for temporary storage of data. Often, the data remains in the buffer until some external event finishes. A buffer can compensate for the differences in transmission or processing speed between two devices or between …   Dictionary of networking

• Data buffer — In computer science, a buffer is a region of a physical memory storage used to temporarily hold data while it is being moved from one place to another. Typically, the data is stored in a buffer as it is retrieved from an input device (such as a… …   Wikipedia

• Gap buffer — In computer science, a gap buffer is a dynamic array that allows efficient insertion and deletion operations clustered near the same location. Gap buffers are especially common in text editors, where most changes to the text occur at or near the… …   Wikipedia

• Variable-length buffer — In telecommunication, a variable length buffer is a buffer into which data may be entered at one rate and removed at another rate without changing the data sequence. Most first in first out (FIFO) storage devices are variable length buffers in… …   Wikipedia

• Floor buffer — A floor buffer or floor polisher is an electrical appliance that is used to clean and maintain non carpeted floors, such as hardwood, marble or linoleum.Somewhat resembling a large upright, wide based vacuum cleaner with handlebar controls and… …   Wikipedia

• Кольцевой буфер — Кольцевой буфер. Иллюстрация визуально показывает, что у буфера нет настоящего конца. Тем не менее, поскольку физическая память никогда не делается закольцованной, обычно используется линейное представление, как показано ниже …   Википедия