Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | File List | Namespace Members | Class Members | File Members | Related Pages

Tools/RingBuffer.h

Go to the documentation of this file.
00001 /**
00002  * @file RingBuffer.h
00003  *
00004  * Declaration of class RingBuffer
00005  *
00006  * @author Max Risler
00007  */
00008 
00009 #ifndef __RingBuffer_h_
00010 #define __RingBuffer_h_
00011 
00012 /**
00013  * @class RingBuffer
00014  *
00015  * template class for cyclic buffering of the last n values of Type V
00016  */
00017 template <class V, int n> class RingBuffer
00018 {
00019   public:
00020     /** Constructor */
00021     RingBuffer() {init();}
00022 
00023     /**
00024      * initializes the Ringbuffer
00025      */
00026     void init () {current = n - 1; numberOfEntries = 0;}
00027 
00028     /**
00029      * adds an entry to the buffer
00030      * \param v value to be added
00031      */
00032     void add (const V& v) 
00033     {
00034       current++;
00035       if (current==n) current=0;
00036       if (++numberOfEntries >= n) numberOfEntries = n;
00037       buffer[current] = v;
00038     }
00039 
00040     /**
00041      * returns an entry
00042      * \param i index of entry counting from last added (last=0,...)
00043      * \return a reference to the buffer entry
00044      */
00045     V& getEntry (int i)
00046     {
00047       int j = current - i;
00048       j %= n;
00049       if (j < 0) j += n;
00050       return buffer[j];
00051    }
00052 
00053    /**
00054      * returns an entry
00055      * \param v the value the entry i shall be updated with
00056      * \param i index of entry counting from last added (last=0,...)
00057      */
00058     void updateEntry(const V& v, int i)
00059     {
00060       int j = current - i;
00061       j %= n;
00062       if (j < 0) j += n;
00063       buffer[j] = v;
00064    }
00065 
00066     /**
00067      * returns an entry
00068      * \param i index of entry counting from last added (last=0,...)
00069      * \return a reference to the buffer entry
00070      */
00071     V& operator[] (int i)
00072     {
00073       return getEntry(i);
00074     }
00075 
00076     /**
00077      * returns a constant entry.
00078      * \param i index of entry counting from last added (last=0,...)
00079      * \return a reference to the buffer entry
00080      */
00081     const V& operator[] (int i) const
00082     {
00083       return buffer[i > current ? n + current - i : current - i];
00084     }
00085 
00086     int getNumberOfEntries() const
00087     {
00088       return numberOfEntries;
00089     }
00090 
00091   private:
00092     int current;
00093     int numberOfEntries;
00094     V buffer[n];
00095 };
00096 
00097 #endif // __RingBuffer_h_

Generated on Mon Mar 20 22:00:09 2006 for GT2005 by doxygen 1.3.6