aboutsummaryrefslogtreecommitdiff
path: root/ring-buffer.c
blob: 537fb906308a63c4bb5a1e3fe4f8c93c61b1ce67 (plain) (blame)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "ring-buffer.h"
#include <stdlib.h>

struct RingBuffer {
	int cur;            /* index of current element, last added etc. */
	int start;          /* index of first/oldest element */
	int end;            /* index of reserved/empty slot */
	size_t size;        /* buffer capacity / number of slots */
	bool iterating;     /* whether we are in a sequence of prev/next calls */
	const void *data[]; /* user supplied buffer content */
};

static int ringbuf_index_prev(RingBuffer *buf, int i) {
	return (i-1+buf->size) % buf->size;
}

static int ringbuf_index_next(RingBuffer *buf, int i) {
	return (i+1) % buf->size;
}

static bool ringbuf_isfull(RingBuffer *buf) {
	return ringbuf_index_next(buf, buf->end) == buf->start;
}

static bool ringbuf_isempty(RingBuffer *buf) {
	return buf->start == buf->end;
}

static bool ringbuf_isfirst(RingBuffer *buf) {
	return buf->cur == buf->start;
}

static bool ringbuf_islast(RingBuffer *buf) {
	return ringbuf_index_next(buf, buf->cur) == buf->end;
}

const void *ringbuf_prev(RingBuffer *buf) {
	if (ringbuf_isempty(buf) || (ringbuf_isfirst(buf) && buf->iterating))
		return NULL;
	if (buf->iterating)
		buf->cur = ringbuf_index_prev(buf, buf->cur);
	buf->iterating = true;
	return buf->data[buf->cur];
}

const void *ringbuf_next(RingBuffer *buf) {
	if (ringbuf_isempty(buf) || ringbuf_islast(buf))
		return NULL;
	buf->cur = ringbuf_index_next(buf, buf->cur);
	buf->iterating = true;
	return buf->data[buf->cur];
}

void ringbuf_add(RingBuffer *buf, const void *value) {
	if (ringbuf_isempty(buf)) {
		buf->end = ringbuf_index_next(buf, buf->end);
	} else if (!ringbuf_islast(buf)) {
		buf->cur = ringbuf_index_next(buf, buf->cur);
		buf->end = ringbuf_index_next(buf, buf->cur);
	} else if (ringbuf_isfull(buf)) {
		buf->start = ringbuf_index_next(buf, buf->start);
		buf->cur = ringbuf_index_next(buf, buf->cur);
		buf->end = ringbuf_index_next(buf, buf->end);
	} else {
		buf->cur = ringbuf_index_next(buf, buf->cur);
		buf->end = ringbuf_index_next(buf, buf->end);
	}
	buf->data[buf->cur] = value;
	buf->iterating = false;
}

void ringbuf_invalidate(RingBuffer *buf) {
	buf->iterating = false;
}

RingBuffer *ringbuf_alloc(size_t size) {
	RingBuffer *buf;
	if ((buf = calloc(1, sizeof(*buf) + (++size)*sizeof(buf->data[0]))))
		buf->size = size;
	return buf;
}

void ringbuf_free(RingBuffer *buf) {
	free(buf);
}