• Main Page
  • Related Pages
  • Namespaces
  • Classes
  • Files
  • File List
  • File Members

include/FCam/CircularBuffer.h

00001 #ifndef FCAM_CIRCULAR_BUFFER_H
00002 #define FCAM_CIRCULAR_BUFFER_H
00003 
00004 #include <stdlib.h>
00005 
00006 namespace FCam {
00007 
00008 // A circular buffer to be used as a memory of recent events. You push
00009 // stuff on, and then ask for the nth last thing you pushed on using
00010 // operator[]. Giving operator[] an argument greater than the size
00011 // returns a bad element.
00012 template<typename T>
00013 class CircularBuffer {
00014 public:
00015     CircularBuffer(size_t s) {
00016         allocated = s;
00017         memory = new T[s];
00018         start = end = 0;
00019     }
00020 
00021     ~CircularBuffer() {
00022         delete[] memory;
00023         memory = NULL;
00024         start = end = allocated = 0;
00025     }
00026 
00027     T &operator[](size_t i) {
00028         return memory[(end - 1 - i + allocated) % allocated];
00029     }
00030 
00031     const T &operator[](size_t i) const {
00032         return memory[(end - 1 - i + allocated) % allocated];
00033     }
00034 
00035     size_t size() const {
00036         if (end >= start) return end-start;
00037         else return end - start + allocated;
00038     }
00039 
00040     void push(T obj) {
00041         memory[end] = obj;
00042         end++;
00043         if (end == allocated) end = 0;
00044 
00045         // if we ate our tail, update the start pointer too
00046         if (end == start) {
00047             start++;
00048             if (start == allocated) start = 0;
00049         }
00050     }
00051 
00052 
00053 private:
00054     size_t start, end;
00055     size_t allocated;
00056     T *memory;
00057 };
00058 
00059 }
00060 
00061 #endif

Generated on Fri Sep 24 2010 15:52:59 for FCam by  doxygen 1.7.1