00001
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036 #ifndef RingBuffer_h
00037 #define RingBuffer_h
00038
00039 #include <rtm/RTC.h>
00040
00041 #include <vector>
00042 #include <algorithm>
00043
00044 #include <rtm/BufferBase.h>
00045
00046 namespace RTC
00047 {
00048 template <class DataType>
00049 class RingBuffer
00050 : public BufferBase<DataType>
00051 {
00052 public:
00053 RingBuffer(long int length)
00054 : m_length(length < 2 ? 2 : length),
00055 m_oldPtr(0),
00056 m_newPtr(length < 2 ? 1 : length - 1)
00057 {
00058 m_buffer.resize(m_length);
00059 }
00060
00072 virtual ~RingBuffer(){};
00073
00074
00075 void init(DataType& data)
00076 {
00077 for (long int i = 0; i < m_length; ++i)
00078 {
00079 put(data);
00080 }
00081 }
00082
00094 virtual long int length() const
00095 {
00096 return m_length;
00097 }
00098
00110 virtual bool write(const DataType& value)
00111 {
00112 put(value);
00113 return true;
00114 }
00115
00127 virtual bool read(DataType& value)
00128 {
00129 value = get();
00130 return true;
00131 }
00132
00144 virtual bool isFull() const
00145 {
00146 return false;
00147 }
00159 virtual bool isEmpty() const
00160 {
00161 return !(this->isNew());
00162 }
00163
00164 bool isNew() const
00165 {
00166 return m_buffer[m_newPtr].isNew();
00167 }
00168
00169 protected:
00181 virtual void put(const DataType& data)
00182 {
00183 m_buffer[m_oldPtr].write(data);
00184
00185 m_newPtr = m_oldPtr;
00186 m_oldPtr = (++m_oldPtr) % m_length;
00187 }
00188
00200 virtual const DataType& get()
00201 {
00202 return m_buffer[m_newPtr].read();
00203 }
00204
00216 virtual DataType& getRef()
00217 {
00218 return m_buffer[m_newPtr].data;
00219 }
00220
00221 private:
00222 long int m_length;
00223 long int m_oldPtr;
00224 long int m_newPtr;
00225
00233 template <class D>
00234 class Data
00235 {
00236 public:
00237 Data() : data(), is_new(false){;}
00238 inline Data& operator=(const D& other)
00239 {
00240 this->data = other;
00241 this->is_new = true;
00242 return *this;
00243 }
00244 inline void write(const D& other)
00245 {
00246 this->is_new = true;
00247 this->data = other;
00248 }
00249 inline D& read()
00250 {
00251 this->is_new = false;
00252 return this->data;
00253 }
00254 inline bool isNew() const
00255 {
00256 return is_new;
00257 }
00258 D data;
00259 bool is_new;
00260 };
00261
00262 std::vector<Data<DataType> > m_buffer;
00263
00264 };
00265 };
00266
00267 #endif // RingBuffer_h