aboutsummaryrefslogtreecommitdiff
path: root/ringbuff.c
diff options
context:
space:
mode:
Diffstat (limited to 'ringbuff.c')
-rw-r--r--ringbuff.c72
1 files changed, 72 insertions, 0 deletions
diff --git a/ringbuff.c b/ringbuff.c
new file mode 100644
index 0000000..99dc0d8
--- /dev/null
+++ b/ringbuff.c
@@ -0,0 +1,72 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdbool.h>
4#include "util.h"
5
6typedef int T;
7
8struct ring_buffer {
9 int head, tail;
10 T array[8]; /* fit for your needs... */
11};
12
13void
14ring_init(struct ring_buffer *rb)
15{
16 rb->head = rb->tail = 0;
17}
18
19bool
20ring_put(struct ring_buffer *rb, T data)
21{
22 const int next = (rb->head + 1) % NELEM(rb->array);
23
24 if ( next == rb->tail )
25 return false;
26
27 rb->array[rb->head] = data;
28 rb->head = next;
29
30 return true;
31}
32
33bool
34ring_get(struct ring_buffer *rb, T *data)
35{
36 if ( rb->head == rb->tail )
37 return false;
38
39 const int next = (rb->tail + 1) % NELEM(rb->array);
40
41 *data = rb->array[rb->tail];
42 rb->tail = next;
43
44 return true;
45}
46
47void f() { ERROR(""); }
48
49int
50main(void)
51{
52#if 0
53 struct ring_buffer rb;
54 ring_init(&rb);
55#else
56 struct ring_buffer rb = { .head = 0, .tail = 0 };
57#endif
58
59 for ( int i = 0; i != 30; ++i ) {
60 if ( !ring_put(&rb, i) )
61 break;
62 }
63
64 int j;
65 while ( ring_get(&rb, &j) ) {
66 printf("%d\n", j);
67 }
68
69 return EXIT_SUCCESS;
70}
71
72