-
Notifications
You must be signed in to change notification settings - Fork 1
/
ringbuf.c
48 lines (38 loc) · 1.06 KB
/
ringbuf.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
45
46
47
48
#include <string.h>
#include "ringbuf.h"
void cmcm_ringbuf_init(cmcm_ringbuf_t *ringbuf, void *buffer, uint16_t capacity, uint8_t size) {
ringbuf->capacity = capacity;
ringbuf->count = 0;
ringbuf->size = size;
ringbuf->buffer = buffer;
ringbuf->head = buffer;
ringbuf->tail = buffer;
}
uint8_t cmcm_ringbuf_push(cmcm_ringbuf_t *ringbuf, const void *data) {
if (ringbuf->count == ringbuf->capacity) {
// full
return 0;
}
memcpy(ringbuf->head, data, ringbuf->size);
ringbuf->head += ringbuf->size;
if (ringbuf->head == ringbuf->buffer + (ringbuf->size * ringbuf->capacity)) {
// wrap around
ringbuf->head = ringbuf->buffer;
}
ringbuf->count++;
return 1;
}
uint8_t cmcm_ringbuf_pop(cmcm_ringbuf_t *ringbuf, void *data) {
if (ringbuf->count == 0) {
// empty
return 0;
}
memcpy(data, ringbuf->tail, ringbuf->size);
ringbuf->tail += ringbuf->size;
if (ringbuf->tail == ringbuf->buffer + (ringbuf->size * ringbuf->capacity)) {
// wrap around
ringbuf->tail = ringbuf->buffer;
}
ringbuf->count--;
return 1;
}