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:
5:8204677dc3c4
Parent:
4:e15dee1d59ee
--- a/CircularBuffer.h	Fri Sep 20 10:32:30 2013 +0000
+++ b/CircularBuffer.h	Mon Mar 17 17:30:25 2014 +0000
@@ -1,6 +1,8 @@
 #ifndef CIRCULAR_BUFFER_H
 #define CIRCULAR_BUFFER_H
 
+#include <stdint.h>
+
 /** This class implements a static circular buffer.
 */
 template<size_t T>
@@ -56,13 +58,14 @@
     
         uint16_t readIndex, writeIndex;
         uint8_t buffer[T]; 
-    
+        size_t bytesAvailable;
 };
 
 template<size_t T>
 CircularBuffer<T>::CircularBuffer():
-readIndex(T),
-writeIndex(0)
+readIndex(0),
+writeIndex(0),
+bytesAvailable(0)
 {
 }
 
@@ -72,9 +75,10 @@
     uint32_t n = 0;
     while(n < length && getSize() > 0)
     {
+        data[n++] = buffer[readIndex++];
         if(readIndex == T)
             readIndex = 0;
-        data[n++] = buffer[readIndex++];
+        --bytesAvailable;
     }
     
     return n;
@@ -86,11 +90,12 @@
     uint32_t n = 0;
     while(n < length && getSize() < T)
     {
+        buffer[writeIndex++] = data[n++];
         if(writeIndex == T)
             writeIndex = 0;
-        buffer[writeIndex++] = data[n++];
+        ++bytesAvailable;
     }
-    
+        
     return n;
 }
 
@@ -103,7 +108,7 @@
 template<size_t T>
 uint32_t CircularBuffer<T>::getSize() const
 {
-    return ((writeIndex > readIndex) ? (writeIndex - readIndex) : (T + writeIndex - readIndex));
+    return bytesAvailable;
 }
 
 template<size_t T>