Skip to content

Commit 1b64d47

Browse files
committed
New Post
1 parent 79a5f80 commit 1b64d47

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
---
2+
layout: post
3+
title: A Simple Array Based Ring Buffer
4+
categories: programming
5+
date: 2024-01-28 13:39:05 +0530
6+
---
7+
8+
The other day, at work, I was trying to design a simple ring buffer which is array based. It had simple requirements - it is an array based buffer with a fixed number of entries (`n`) and keeps overwriting the least recent entry once the array is full. When accessed, it need to visit the entries from the least recent to the most recent item.
9+
10+
All we need is a simple structure and two variables:
11+
12+
```c
13+
typedef struct element_s {
14+
// your data definition goes here
15+
} element_t;
16+
17+
element_t ring_buffer[MAX_ENTRIES]; //An array of maximum entries
18+
int next_index = -1;
19+
```
20+
21+
Adding entries to the ring buffer is simple:
22+
23+
```c
24+
void
25+
add(element)
26+
{
27+
next_index = (next_index + 1) % MAX_ENTRIES;
28+
ring_buffer[next_index] = element;
29+
}
30+
```
31+
32+
Looping through the entries from the least recent to the most recent is also simple:
33+
34+
```c
35+
void
36+
iterate()
37+
{
38+
if (next_index == -1) {
39+
return;
40+
41+
idx = (next_index + 1) % MAX_ENTRIES;
42+
if (is_zero(ring_buffer[idx])) {
43+
* ring buffer is somewhere in the middle
44+
*/
45+
start = 0;
46+
count = next_index - start;
47+
} else {
48+
/* Every element in the array is written atleast once, so
49+
* visit every element in the array
50+
*/
51+
start = (next_index + 1) % MAX_ENTRIES;
52+
count = MAX_ENTRIES;
53+
}
54+
}
55+
```
56+
57+
The rationale is that when element next to the current index is uninitialized (i.e. never written), then only the elements from the beginning to the current index is written. We need to visit entries from 0 till current index. However, if the element next to the current index is initialized (already written), then every element in the ring buffer is written atleast once and we need to visit the elements from the first index after current index until the current index (for a total of `MAX_ENTRIES`)
58+
59+
It is a very simple implementation!

0 commit comments

Comments
 (0)