Small library for using circular buffers

Dependents:   CircularBufferExample

This library provides circular buffers. The main difference with other circular buffer libraries is that it does not use dynamic memory allocation for storing data. Instead, the buffer is allocated statically.

Three types of buffer exist by default :

  • SmallCircularBuffer (32 bytes)
  • MediumCircularBuffer (128 bytes)
  • BigCircularBuffer (512 bytes)

You can also define buffers with specific size :

CircularBuffer<4> buffer;    // 4 bytes buffer
CircularBuffer<102> buffer2; // 102 bytes buffer

Import programCircularBufferExample

This example shows how to use the CircularBuffer library.

Revision:
0:5d058c917599
Child:
1:9953890d59e2
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CircularBuffer.h	Mon Sep 16 14:35:39 2013 +0000
@@ -0,0 +1,60 @@
+#ifndef CIRCULAR_BUFFER_H
+#define CIRCULAR_BUFFER_H
+
+template<size_t T>
+class CircularBuffer
+{
+    public :
+    
+        CircularBuffer();
+        
+        int read(uint8_t *data, uint32_t length);
+        int write(uint8_t *data, uint32_t length);
+          
+    private :
+    
+        uint32_t readIndex, writeIndex;
+        uint8_t buffer[T]; 
+    
+};
+
+template<size_t T>
+CircularBuffer<T>::CircularBuffer():
+readIndex(0),
+writeIndex(1)
+{
+}
+
+template<size_t T>
+int CircularBuffer<T>::read(uint8_t *data, uint32_t length)
+{
+    uint32_t read = 0;
+    while((readIndex+1)%T != writeIndex && read < length)
+    {
+        data[read++] = buffer[readIndex++];
+        if(readIndex == T)
+            readIndex = 0;
+    }
+    
+    return read;
+}
+
+template<size_t T>
+int CircularBuffer<T>::write(uint8_t *data, uint32_t length)
+{
+    uint32_t wrote = 0;
+    while(writeIndex != readIndex && wrote < length)
+    {
+        buffer[writeIndex++] = data[wrote++];
+        if(writeIndex == T)
+            writeIndex = 0;
+    }
+    
+    return wrote;
+}
+
+typedef CircularBuffer<32> SmallCircularBuffer;
+typedef CircularBuffer<128> MediumCircularBuffer;
+typedef CircularBuffer<512> BigCircularBuffer;
+
+#endif