00001 #ifndef FCAM_CIRCULAR_BUFFER_H
00002 #define FCAM_CIRCULAR_BUFFER_H
00003
00004 #include <stdlib.h>
00005
00006 namespace FCam {
00007
00008
00009
00010
00011
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
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