1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2016 Edouard Griffiths, F4EXB. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef DOUBLEBUFFER_H_
#define DOUBLEBUFFER_H_
#include <string.h>
#include <assert.h>
namespace DSDcc
{
template<typename T>
class DoubleBuffer
{
public:
explicit DoubleBuffer(unsigned int size) :
m_size(size),
m_index(0)
{
assert(m_size > 0);
m_buffer = new T[2*m_size];
reset();
}
DoubleBuffer(const DoubleBuffer& other) :
m_size(other.m_size),
m_index(other.m_index)
{
m_buffer = new T[2*m_size];
memcpy(m_buffer, other.m_buffer, 2*m_size*sizeof(T));
reset();
}
DoubleBuffer& operator=(const DoubleBuffer& other)
{
if (&other == this) {
return *this;
}
m_size = other.m_size;
m_index = other.m_index;
m_buffer = new T[2*m_size];
memcpy(m_buffer, other.m_buffer, 2*m_size*sizeof(T));
reset();
return *this;
}
~DoubleBuffer()
{
delete[] m_buffer;
}
void resize(unsigned int size)
{
delete[] m_buffer;
m_size = size;
m_buffer = new T[2*m_size];
reset();
}
void push(T item)
{
m_buffer[m_index] = item;
m_buffer[m_index + m_size] = item;
m_index = (m_index + 1) % m_size;
}
void reset()
{
m_index = 0;
memset(m_buffer, 0, 2*m_size*sizeof(T));
}
void move(int distance)
{
m_index = (m_index + m_size + distance) % m_size;
}
T *getData(unsigned int shift = 0) // point to oldest by default
{
if (shift < m_size)
{
return &m_buffer[m_index+shift];
}
else
{
return &m_buffer[m_index]; // oldest
}
}
T& getLatest()
{
return m_buffer[m_index + m_size - 1];
}
T* getBack(unsigned int shift = 0) // point to oldest by default
{
if (shift < m_size)
{
return &m_buffer[(m_index + m_size - shift) % m_size];
}
else
{
return &m_buffer[m_index]; // oldest
}
}
private:
unsigned int m_size;
int m_index;
T *m_buffer;
};
} // namespace DSDcc
#endif /* DOUBLEBUFFER_H_ */
|