ringbuf/ringbuf.c

29 lines
818 B
C
Raw Normal View History

2024-06-23 14:08:57 +02:00
/* SPDX-License-Identifier: MIT */
#include "ringbuf.h"
void rb_init(struct RingBuf *rb, int capacity, void *(*alloc)(int),
int struct_size) {
rb->struct_size = struct_size;
rb->capacity = capacity;
rb->write_idx = 0;
rb->read_idx = 0;
rb->buffer = alloc(capacity * struct_size); /* Calloc? */
}
void rb_destroy(struct RingBuf *rb, int(free)(void *)) { free(rb->buffer); }
2024-06-23 14:15:56 +02:00
enum WriteResult rb_push(struct RingBuf *rb, void *data[], int amount,
int (*memcpy)(void *, const void *, int)) {
2024-06-23 14:08:57 +02:00
if (rb->write_idx == rb->read_idx) {
return CollisionError;
}
2024-06-23 14:15:56 +02:00
for (int i = 0; i < amount; i++) {
memcpy(rb->buffer + rb->write_idx * rb->struct_size, data[i],
rb->struct_size);
rb->write_idx = (rb->write_idx + 1) % rb->capacity;
}
2024-06-23 14:08:57 +02:00
return Ok;
}