-
Notifications
You must be signed in to change notification settings - Fork 82
/
ringbuf.h
145 lines (121 loc) · 2.13 KB
/
ringbuf.h
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
#pragma once
/*
#define RB_ATOMIC_START disableInterrupts()
#define RB_ATOMIC_END enbleInterrupts()
int u32 lastInterrupts = 0;
void disableInterrupts(void)
{
__asm volatile ( \
" mrs %0, primask\n" \
: "=r" (lastInterrupts) \
" mov r0, #1 \n" \
" msr primask, r0\n" \
:::"r0" \
);
}
void enableInterrupts(void)
{
__asm volatile ( \
" msr primask, %0\n" \
:: "r" (lastInterrupts) \
);
}
*/
#define RB_ATOMIC_START
#define RB_ATOMIC_END
template <typename Type, size_t MaxElements>
class RingBuffer
{
public:
RingBuffer()
{
RB_ATOMIC_START
{
_numElements = 0;
_head = 0;
}
RB_ATOMIC_END
}
void empty()
{
RB_ATOMIC_START
{
_numElements = 0;
_head = 0;
}
RB_ATOMIC_END
}
bool push(Type obj)
{
bool ret = false;
RB_ATOMIC_START
{
if (!isFull())
{
_buf[_head] = obj;
_head = (_head + 1)%MaxElements;
_numElements++;
ret = true;
}
}
RB_ATOMIC_END
return ret;
}
Type pull()
{
size_t tail;
RB_ATOMIC_START
{
if (size() > 0) {
tail = getTail();
Type dest = _buf[tail];
_numElemen
ts--;
return dest; // ATOMIC???
}
}
RB_ATOMIC_END
return -1;
}
Type peek()
{
size_t tail;
RB_ATOMIC_START
{
if (size() > 0) {
tail = getTail();
return _buf[tail];// ATOMIC???
}
}
RB_ATOMIC_END
return -1;
}
bool isFull()
{
bool ret;
RB_ATOMIC_START
{
ret = _numElements >= MaxElements;
}
RB_ATOMIC_END
return ret;
}
size_t size()
{
size_t ret;
RB_ATOMIC_START
{
ret = _numElements;
}
RB_ATOMIC_END
return ret;
}
protected:
size_t getTail()
{
return (_head + (MaxElements - _numElements))%MaxElements;
}
Type _buf[MaxElements];
size_t _head;
size_t _numElements;
};