// Ring buffer
//
// Simplified code as example for the ring buffer.
//
// by feyd//godX.de
#include <cstdint>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
template<class _TYPE>
class CRingBuffer : public std::vector<_TYPE>
{
public:
CRingBuffer(size_t nSize) :
std::vector<_TYPE>(nSize), m_nReadPos(0), m_nWritePos(0), m_nLength(0) {}
virtual ~CRingBuffer() {}
bool IsEmpty() const
{
return m_nLength==0;
}
size_t GetSpace() const
{
return (*this).size()-m_nLength;
}
bool Push(const _TYPE& element)
{
if(GetSpace()==0)
return false;
(*this)[m_nWritePos++] = element;
if(m_nWritePos>=(*this).size())
m_nWritePos = 0;
m_nLength++;
return true;
}
_TYPE Pop()
{
if(IsEmpty())
return _TYPE();
m_nLength--;
int nReadPos = m_nReadPos++;
if(m_nReadPos>=(*this).size())
m_nReadPos = 0;
return (*this)[nReadPos];
}
void Debug() const
{
printf("Capacity: %d/%d Read (>): %d Write (<): %d | ", (int)m_nLength, (int)(*this).size(), (int)m_nReadPos, (int)m_nWritePos);
for(size_t n=0; n<=(*this).size(); n++)
{
if(n==m_nReadPos)
printf("> ");
if(n==m_nWritePos)
printf("< ");
if(n<(*this).size())
printf("%d ", (*this)[n]);
}
printf("\r\n");
}
private:
size_t m_nReadPos;
size_t m_nWritePos;
size_t m_nLength;
};
// Application entry point (from libc)
int main(int argc, const char* argv[])
{
printf("Ring buffer test...\r\n\r\n");
if(argc<2)
{
printf("Not enough parameters.\r\n");
return -1;
}
CRingBuffer<int> buffer(atoi(argv[1]));
for(int n=2; n<argc; n++)
{
if(argv[n][0]=='p')
{
if(!buffer.IsEmpty())
{
printf(" Popped %d\r\n", buffer.Pop());
} else {
printf(" Can't pop ... buffer empty!\r\n");
}
} else if(argv[n][0]=='d') {
printf(" Debug ");
buffer.Debug();
} else {
int nCode = atoi(argv[n]);
if(buffer.Push(nCode))
{
printf(" Pushed %d\r\n", nCode);
} else {
printf(" Can't push %d ... buffer full\r\n", nCode);
}
}
}
return 0;
}
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