@@ -114,6 +114,8 @@ class CircularBuffer {
114
114
*/
115
115
void push (const T *src, CounterType len)
116
116
{
117
+ MBED_ASSERT (len > 0 );
118
+
117
119
core_util_critical_section_enter ();
118
120
119
121
/* if we try to write more bytes than the buffer can hold we only bother writing the last bytes */
@@ -129,23 +131,21 @@ class CircularBuffer {
129
131
CounterType written = len;
130
132
131
133
/* on first pass we write as much as we can to the right of head */
132
- if ((_head + len ) > BufferSize) {
134
+ if ((_head + written ) > BufferSize) {
133
135
written = BufferSize - _head;
134
136
}
135
137
136
138
std::copy (src, src + written, _buffer + _head);
139
+ _head = incrementCounter (_head, written);
137
140
138
141
CounterType left_to_write = len - written;
139
142
140
143
/* we might need to continue to write from the start of the buffer */
141
144
if (left_to_write) {
142
145
std::copy (src + written, src + written + left_to_write, _buffer);
143
- written + = left_to_write;
146
+ _head = left_to_write;
144
147
}
145
148
146
- _head += written;
147
- _head %= BufferSize;
148
-
149
149
if (adjust_tail) {
150
150
_tail = _head;
151
151
_full = true ;
@@ -198,6 +198,8 @@ class CircularBuffer {
198
198
*/
199
199
CounterType pop (T *dest, CounterType len)
200
200
{
201
+ MBED_ASSERT (len > 0 );
202
+
201
203
if (len == 0 ) {
202
204
return 0 ;
203
205
}
@@ -219,18 +221,18 @@ class CircularBuffer {
219
221
}
220
222
221
223
std::copy (_buffer + _tail, _buffer + _tail + data_popped, dest);
224
+ _tail = incrementCounter (_tail, data_popped);
222
225
223
226
/* if we looped over the end we may need to pop again */
224
227
CounterType left_to_pop = len - data_popped;
225
228
226
229
if (left_to_pop) {
227
230
std::copy (_buffer, _buffer + left_to_pop, dest + data_popped);
231
+ _tail = left_to_pop;
228
232
229
233
data_popped += left_to_pop;
230
234
}
231
235
232
- _tail += data_popped;
233
- _tail %= BufferSize;
234
236
_full = false ;
235
237
}
236
238
@@ -335,9 +337,23 @@ class CircularBuffer {
335
337
return elements;
336
338
}
337
339
338
- CounterType incrementCounter (CounterType val)
340
+ /* * Used to increment _tail or _head by a given value.
341
+ *
342
+ * @param val The value of the counter to be incremented.
343
+ * @param increment The amount to be added, the value after this incremented must not exceed BufferSize.
344
+ * @return The new value of the counter.
345
+ */
346
+ CounterType incrementCounter (CounterType val, CounterType increment = 1 )
339
347
{
340
- return (++val) % BufferSize;
348
+ val += increment;
349
+
350
+ MBED_ASSERT (val <= BufferSize);
351
+
352
+ if (val == BufferSize) {
353
+ val = 0 ;
354
+ }
355
+
356
+ return val;
341
357
}
342
358
343
359
private:
0 commit comments