changed RingBufferHistory to use qvector instead of raw array

This commit is contained in:
wangyix 2014-07-10 11:55:19 -07:00
parent 0b213f9616
commit a955a17472

View file

@ -15,6 +15,8 @@
#include <stdlib.h>
#include <iterator>
#include <qvector.h>
template <typename T>
class RingBufferHistory {
@ -24,34 +26,9 @@ public:
: _size(capacity + 1),
_capacity(capacity),
_newestEntryAtIndex(0),
_numEntries(0)
_numEntries(0),
_buffer(capacity + 1)
{
_buffer = new T[_size];
}
RingBufferHistory(const RingBufferHistory& other)
: _size(other._size),
_capacity(other._capacity),
_newestEntryAtIndex(other._newestEntryAtIndex),
_numEntries(other._numEntries)
{
_buffer = new T[_size];
memcpy(_buffer, other._buffer, _size*sizeof(T));
}
RingBufferHistory& operator= (const RingBufferHistory& rhs) {
_size = rhs._size;
_capacity = rhs._capacity;
_newestEntryAtIndex = rhs._newestEntryAtIndex;
_numEntries = rhs._numEntries;
delete[] _buffer;
_buffer = new T[_size];
memcpy(_buffer, rhs._buffer, _size*sizeof(T));
return *this;
}
~RingBufferHistory() {
delete[] _buffer;
}
void clear() {
@ -98,22 +75,16 @@ public:
int getNumEntries() const { return _numEntries; }
private:
T* _buffer;
int _size;
int _capacity;
int _newestEntryAtIndex;
int _numEntries;
QVector<T> _buffer;
public:
class Iterator : public std::iterator < std::forward_iterator_tag, T > {
public:
Iterator(T* buffer, int size, T* at) : _buffer(buffer), _bufferEnd(buffer+size), _at(at) {}
Iterator& operator=(const Iterator& other) {
_buffer = other._buffer;
_bufferEnd = other._bufferEnd;
_at = other._at;
}
Iterator(T* bufferFirst, T* bufferLast, T* at) : _bufferFirst(bufferFirst), _bufferLast(bufferLast), _at(at) {}
bool operator==(const Iterator& rhs) { return _at == rhs._at; }
bool operator!=(const Iterator& rhs) { return _at != rhs._at; }
@ -121,7 +92,7 @@ public:
T* operator->() { return _at; }
Iterator& operator++() {
_at = (_at == _buffer) ? _bufferEnd - 1 : _at - 1;
_at = (_at == _bufferFirst) ? _bufferLast : _at - 1;
return *this;
}
@ -132,19 +103,19 @@ public:
}
private:
T* const _buffer;
T* const _bufferEnd;
T* const _bufferFirst;
T* const _bufferLast;
T* _at;
};
Iterator begin() { return Iterator(_buffer, _size, &_buffer[_newestEntryAtIndex]); }
Iterator begin() { return Iterator(&_buffer.first(), &_buffer.last(), &_buffer[_newestEntryAtIndex]); }
Iterator end() {
int endAtIndex = _newestEntryAtIndex - _numEntries;
if (endAtIndex < 0) {
endAtIndex += _size;
}
return Iterator(_buffer, _size, &_buffer[endAtIndex]);
return Iterator(&_buffer.first(), &_buffer.last(), &_buffer[endAtIndex]);
}
};