-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcircular_buffer.c
44 lines (37 loc) · 1004 Bytes
/
circular_buffer.c
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
#include "circular_buffer.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
int circular_buffer_init(struct circular_buffer_t *b, size_t sz) {
memset(b, 0, sizeof(*b));
b->sz = sz;
b->buf = (char*)malloc(sz);
if (!b->buf)
return -1;
return 0;
}
void circular_buffer_destroy(struct circular_buffer_t *b) {
free(b->buf);
}
size_t circular_buffer_get_free(struct circular_buffer_t *b) {
return b->hbehind? (b->tail - b->head) : (b->sz - b->head);
}
size_t circular_buffer_get_ready(struct circular_buffer_t *b) {
return b->hbehind? (b->sz - b->tail) : (b->head - b->tail);
}
void circular_buffer_advance_head(struct circular_buffer_t *b, size_t s) {
assert (s <= circular_buffer_get_free(b));
b->head += s;
if (b->head == b->sz) {
b->head = 0;
b->hbehind = true;
}
}
void circular_buffer_advance_tail(struct circular_buffer_t *b, size_t s) {
assert (s <= circular_buffer_get_ready(b));
b->tail += s;
if (b->tail == b->sz) {
b->tail = 0;
b->hbehind = false;
}
}