ringbuf/ringbuf.c

31 lines
873 B
C
Raw Normal View History

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