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

CircularBuffer.h

Committer:
feb11
Date:
2013-09-20
Revision:
3:9a45d6675e65
Parent:
2:6f3630f5fa06
Child:
4:e15dee1d59ee

File content as of revision 3:9a45d6675e65:

#ifndef CIRCULAR_BUFFER_H
#define CIRCULAR_BUFFER_H

template<size_t T>
class CircularBuffer
{
    public :
    
        CircularBuffer();
        
        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;  
        bool isEmpty() const;
        bool isFull() const;
        
    private :
    
        uint16_t readIndex, writeIndex;
        uint8_t buffer[T]; 
    
};

template<size_t T>
CircularBuffer<T>::CircularBuffer():
readIndex(T),
writeIndex(0)
{
}

template<size_t T>
uint32_t CircularBuffer<T>::read(uint8_t *data, uint32_t length)
{
    uint32_t n = 0;
    while(n < length && getSize() > 0)
    {
        if(readIndex == T)
            readIndex = 0;
        data[n++] = buffer[readIndex++];
    }
    
    return n;
}

template<size_t T>
uint32_t CircularBuffer<T>::write(uint8_t *data, uint32_t length)
{
    uint32_t n = 0;
    while(n < length && getSize() < T)
    {
        if(writeIndex == T)
            writeIndex = 0;
        buffer[writeIndex++] = data[n++];
    }
    
    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) ? (writeIndex - readIndex) : (T + writeIndex - readIndex));
}

template<size_t T>
bool CircularBuffer<T>::isEmpty() const
{
    return getSize() == 0;
}

template<size_t T>
bool CircularBuffer<T>::isFull() const
{
    return getSize() == T;
}

typedef CircularBuffer<32> SmallCircularBuffer;
typedef CircularBuffer<128> MediumCircularBuffer;
typedef CircularBuffer<512> BigCircularBuffer;

#endif