aboutsummaryrefslogtreecommitdiff
path: root/ringbuff.c
blob: 99dc0d814fc23e88d562481cc5f9c1b9a4d28e2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "util.h"

typedef int T;

struct ring_buffer {
	int head, tail;
	T array[8];	/* fit for your needs... */
};

void
ring_init(struct ring_buffer *rb)
{
	rb->head = rb->tail = 0;
}

bool
ring_put(struct ring_buffer *rb, T data)
{
	const int next = (rb->head + 1) % NELEM(rb->array);

	if ( next == rb->tail )
		return false;

	rb->array[rb->head] = data;
	rb->head = next;

	return true;
}

bool
ring_get(struct ring_buffer *rb, T *data)
{
	if ( rb->head == rb->tail )
		return false;

	const int next = (rb->tail + 1) % NELEM(rb->array);

	*data = rb->array[rb->tail];
	rb->tail = next;

	return true;
}

void f() { ERROR(""); }

int
main(void)
{
#if 0
	struct ring_buffer rb;
	ring_init(&rb);
#else
	struct ring_buffer rb = { .head = 0, .tail = 0 };
#endif

	for ( int i = 0; i != 30; ++i ) {
		if ( !ring_put(&rb, i) )
			break;
	}

	int j;
	while ( ring_get(&rb, &j) ) {
		printf("%d\n", j);
	}

	return EXIT_SUCCESS;
}