Small library for using circular buffers (forked from François Berder's implementation in order to add methods and fix problems)

Dependents:   CircularBufferTest XBeeApi

Fork of CircularBuffer by Francois Berder

Test suite can be found in this application, CircularBufferTest

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