-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathRingBuffer.h
More file actions
151 lines (123 loc) · 2.51 KB
/
RingBuffer.h
File metadata and controls
151 lines (123 loc) · 2.51 KB
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#ifndef _RINGBUFFER_H_
#define _RINGBUFFER_H_
/* 'Thread'safe RingBuffer for Atmega.
* (c) 2011, Christopher "ScribbleJ" Jansen
*
* Note: Safety only assured if all writes from the same 'thread' and all reads from the same 'thread'. Mixing them is no good.
*
*/
#include <util/atomic.h>
typedef uint16_t RB_SIZE_TYPE;
template<typename T> class RingBufferT
{
public:
typedef T DTYPE;
private:
const RB_SIZE_TYPE size;
volatile RB_SIZE_TYPE count;
DTYPE* start;
DTYPE* end;
DTYPE* head;
DTYPE* tail;
public:
RingBufferT(RB_SIZE_TYPE size, DTYPE* data) :
size(size), count(0), start(data), end(data + size), head(data), tail(data)
{};
inline void reset()
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
head = start;
tail = start;
count = 0;
}
}
inline void push(DTYPE const& d)
{
*tail = d;
if(++tail == end)
tail = start;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
count++;
}
}
inline DTYPE pop()
{
DTYPE d = *head;
if(++head == end)
head = start;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
count--;
}
return d;
}
inline const RB_SIZE_TYPE getCount()
{
RB_SIZE_TYPE c;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
c = count;
}
return c;
}
inline const RB_SIZE_TYPE getCapacity()
{
return (size - getCount());
}
inline const bool isEmpty()
{
return (getCount() == 0);
}
inline const bool isFull()
{
return (getCount() >= size);
}
inline DTYPE& peek(RB_SIZE_TYPE index)
{
//return *(head+index);
DTYPE *t = head;
for(;index > 0;index--)
{
t++;
if(t == end)
t = start;
}
return *(t);
}
inline void remove(RB_SIZE_TYPE count_in)
{
for(RB_SIZE_TYPE c = count_in;c > 0;c--)
{
if(++head == end)
head = start;
}
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
count-=count_in;
}
}
inline DTYPE& getNextWrite(RB_SIZE_TYPE index)
{
DTYPE* dp = tail;
while(index > 0)
{
index--;
dp++;
if(dp == end) dp = start;
}
return *dp;
}
inline void finishWrite()
{
tail++;
if(tail == end)
tail = start;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
count++;
}
}
};
#endif // _RINGBUFFER_H_