0 day streak
cpp / expert
Snippet

Statically Allocated Ring Buffer for Embedded Systems

A circular buffer (ring buffer) using a fixed-size array is essential for real-time systems to avoid dynamic memory allocation. By using a static array and modulo-based indexing, this implementation provides O(1) time complexity for both insertion and removal while maintaining a zero-allocation footprint.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template<typename T, size_t Capacity>
class CircularBuffer {
T storage[Capacity];
size_t head = 0;
size_t tail = 0;
bool full = false;
public:
void push(T item) {
storage[head] = item;
if (full) tail = (tail + 1) % Capacity;
head = (head + 1) % Capacity;
full = head == tail;
}
T pop() {
if (head == tail && !full) return T{};
T item = storage[tail];
full = false;
tail = (tail + 1) % Capacity;
return item;
}
};
Breakdown
1
T storage[Capacity];
The contiguous memory block allocated at compile-time.
2
(head + 1) % Capacity
The modulo operator wraps the index back to the start of the array.