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:
5:abe8909f9603
Parent:
4:e15dee1d59ee
Child:
6:242d0e9f13d1
--- a/CircularBuffer.h	Fri Sep 20 10:32:30 2013 +0000
+++ b/CircularBuffer.h	Sat Jan 18 17:56:32 2014 +0000
@@ -1,18 +1,26 @@
 #ifndef CIRCULAR_BUFFER_H
 #define CIRCULAR_BUFFER_H
 
+#include <cstddef>
+#include <stdint.h>
+
 /** This class implements a static circular buffer.
+
+    CirularBuffer class originally by François Berder ( see http://mbed.org/users/feb11/code/CircularBuffer/ )
+    Additions by John Bailey ( http://mbed.org/users/johnb/ )
 */
 template<size_t T>
 class CircularBuffer
 {
     public :
-    
+
         /** Default constructor
         */
         CircularBuffer();
         
-        /** Reads data from buffer
+        /** Reads data from buffer (data is removed from the buffer as 
+            opposed to the peek method which allows inspection of the
+            contents without modifying the buffer)
         
             \param data output buffer 
             \param length Maximum number of bytes to read
@@ -21,6 +29,18 @@
             \note The return value cannot exceed max(length,capacity)
         */
         uint32_t read(uint8_t *data, uint32_t length);
+
+        /** Reads data from buffer leaving the data in the buffer
+            (as opposed to the read method which removed the returned
+            data from the buffer)
+        
+            \param data output buffer 
+            \param length Maximum number of bytes to read
+            \return Number of bytes read
+            
+            \note The return value cannot exceed max(length,capacity)
+        */
+        uint32_t peek(uint8_t *data, uint32_t length) const;
         
         /** Writes data in buffer
         
@@ -53,8 +73,10 @@
         bool isFull() const;
         
     private :
+
+        typedef uint16_t CircularBufferIndex_t;
     
-        uint16_t readIndex, writeIndex;
+        CircularBufferIndex_t readIndex, writeIndex;
         uint8_t buffer[T]; 
     
 };
@@ -81,6 +103,22 @@
 }
 
 template<size_t T>
+uint32_t CircularBuffer<T>::peek(uint8_t *data, uint32_t length) const
+{
+    uint32_t n = 0;
+    CircularBufferIndex_t src = readIndex;
+    while(n < length && getSize() > 0)
+    {
+        if(src == T) {
+            src = 0;
+        }
+        data[n++] = buffer[src++];
+    }
+    
+    return n;
+}
+
+template<size_t T>
 uint32_t CircularBuffer<T>::write(uint8_t *data, uint32_t length)
 {
     uint32_t n = 0;