Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
CircularBuffer.h
- Committer:
- UCSBRobotics
- Date:
- 2012-08-05
- Revision:
- 2:4080c1770d51
- Parent:
- 1:b24970e4c038
- Child:
- 3:1a33490e1990
File content as of revision 2:4080c1770d51:
#ifndef CIRCULARBUFFER_H
#define CIRCULARBUFFER_H
template <typename T, int S>
class CircularBuffer
{
public:
    CircularBuffer() { currentIndex = 0; }
    T read(int index);
    T& operator[](int index);
    void write(T value, int index);
    void push(T value);
    void revert(int amount);
    
protected:
    T data[S];
    int currentIndex;
    inline int getRealIndex(int i);
};
template <typename T, int S>
inline int CircularBuffer<T, S>::getRealIndex(int index)
{
    int realIndex = (currentIndex - index) % S;
    if (realIndex < 0) realIndex += S;
    return realIndex;
}
template <typename T, int S>
inline T CircularBuffer<T, S>::read(int index)
{
    return data[getRealIndex(index)];
}
template <typename T, int S>
inline T& CircularBuffer<T, S>::operator[](int index)
{
    return data[getRealIndex(index)];
}
template <typename T, int S>
inline void CircularBuffer<T, S>::write(T value, int index)
{
    data[getRealIndex(index)] = value;
}
template <typename T, int S>
inline void CircularBuffer<T, S>::push(T value)
{
    currentIndex = ++currentIndex % S;
    data[currentIndex] = value;
}
template <typename T, int S>
inline void CircularBuffer<T, S>::revert(int amount)
{
    currentIndex = currentIndex >= amount ? currentIndex - amount : currentIndex - amount + S;
}
#endif // CIRCULARBUFFER_H
            
    