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:
2:6f3630f5fa06
Parent:
1:9953890d59e2
Child:
3:9a45d6675e65
--- a/CircularBuffer.h	Mon Sep 16 14:54:26 2013 +0000
+++ b/CircularBuffer.h	Fri Sep 20 09:16:45 2013 +0000
@@ -8,54 +8,67 @@
     
         CircularBuffer();
         
-        int read(uint8_t *data, uint32_t length);
-        int write(uint8_t *data, uint32_t length);
-          
+        uint32_t read(uint8_t *data, uint32_t length);
+        uint32_t write(uint8_t *data, uint32_t length);
+        uint32_t getCapacity() const;
+        uint32_t getSize() const;
+        
     private :
     
-        uint32_t readIndex, writeIndex;
+        uint16_t readIndex, writeIndex;
         uint8_t buffer[T]; 
     
 };
 
 template<size_t T>
 CircularBuffer<T>::CircularBuffer():
-readIndex(T),
+readIndex(0),
 writeIndex(0)
 {
 }
 
 template<size_t T>
-int CircularBuffer<T>::read(uint8_t *data, uint32_t length)
+uint32_t CircularBuffer<T>::read(uint8_t *data, uint32_t length)
 {
-    uint32_t read = 0;
-    while(readIndex%T != writeIndex && read < length)
+    uint32_t n = 0;
+    while(n < length && getSize() < T)
     {
-        if(readIndex >= T)
-            readIndex %= T;
-        data[read++] = buffer[readIndex++];
-
+        if(readIndex == T)
+            readIndex = 0;
+        data[n++] = buffer[readIndex++];
     }
     
-    return read;
+    return n;
 }
 
 template<size_t T>
-int CircularBuffer<T>::write(uint8_t *data, uint32_t length)
+uint32_t CircularBuffer<T>::write(uint8_t *data, uint32_t length)
 {
-    uint32_t wrote = 0;
-    while((writeIndex+1)%T != readIndex%T && wrote < length)
+    uint32_t n = 0;
+    while(n < length && getSize() > 0)
     {
-        buffer[writeIndex++] = data[wrote++];
         if(writeIndex == T)
             writeIndex = 0;
+        buffer[writeIndex++] = data[n++];
     }
     
-    return wrote;
+    return n;
+}
+
+template<size_t T>
+uint32_t CircularBuffer<T>::getCapacity() const
+{
+    return T;
+}
+        
+template<size_t T>
+uint32_t CircularBuffer<T>::getSize() const
+{
+    return ((writeIndex >= readIndex) ? (T - writeIndex + readIndex) : (readIndex - writeIndex));
 }
 
 typedef CircularBuffer<32> SmallCircularBuffer;
 typedef CircularBuffer<128> MediumCircularBuffer;
-typedef CircularBuffer<256> BigCircularBuffer;
+typedef CircularBuffer<512> BigCircularBuffer;
 
 #endif