Ring buffer
Implement put and get for a fixed-size FIFO. A medium embedded C problem (Buffers and data structures), run and graded in the browser.
medium · Buffers and data structures · fifo · uart
A ring buffer is the standard way to pass bytes between an interrupt and the main loop. A zero-initialised ring_t is an empty buffer.
ring_putstoresvand returnstrue, or returnsfalsewithout storing when the buffer is full.ring_getremoves the oldest byte into*vand returnstrue, or returnsfalseand leaves*valone when the buffer is empty.
Bytes come out in the order they went in, and the indices wrap around at RB_SIZE.
Starter code
bool ring_put(ring_t *r, uint8_t v) {
// Store v at head, advance head with wrap-around.
return false;
}
bool ring_get(ring_t *r, uint8_t *v) {
// Read from tail, advance tail with wrap-around.
return false;
}Example tests
First in, first out
ring_t r = { 0 };
ring_put(&r, 1); ring_put(&r, 2); ring_put(&r, 3);
uint8_t a = 0, b = 0;
ring_get(&r, &a); ring_get(&r, &b);
printf("%u %u %u\n", a, b, r.count);Expected output:
1 2 1Reading an empty buffer
ring_t r = { 0 };
uint8_t v = 99;
printf("%d %u\n", ring_get(&r, &v), v);Expected output:
0 99Learn it first
- Buffers and data structures · Ring buffers, pools, lists and bitmaps on static memory.
More Buffers and data structures problems
- Fill level from two indices · Compute how many items a FIFO holds from its head and tail.
- Overwriting log buffer · Keep only the most recent entries, replacing the oldest when full.
- Fixed-size stack · Push and pop on an array-backed stack with overflow and underflow checks.
- Sorted insert into a linked list · Insert a caller-provided node into an ascending singly linked list.
- Reverse a linked list · Reverse a singly linked list in place.
- Fixed-block memory pool · Allocate and free fixed-size blocks from a static pool.
- Small priority queue · Keep pending jobs ordered by priority in a fixed array.
- Bitmap operations · Set, clear and test individual bits in a byte array.
- First free slot · Find the first zero bit in a bitmap of a given length.
- Sample history by age · Store the last few samples and read them back by how old they are.
- Bump allocator · Hand out aligned chunks from a static buffer.
- Fix: the console drops characters · A serial console echoes the wrong characters once its receive buffer wraps.
- An opaque FIFO module: fifo.h and fifo.c · Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions.
- Bluetooth speaker: never overwrite unplayed audio · A sample ring buffer that refuses new samples when full instead of overwriting the ones not yet played.