55 lines
1.3 KiB
C
55 lines
1.3 KiB
C
/* SPDX-License-Identifier: MIT */
|
|
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdio.h>
|
|
|
|
#include "ringbuf.h"
|
|
|
|
#define ALLOC_T void *(*alloc)(rb_size_t)
|
|
#define MEMCPY_T void *(*memcpy)(void *, const void *, rb_size_t)
|
|
|
|
void
|
|
rb_init(struct RingBuf *rb, rb_size_t capacity, ALLOC_T, rb_size_t 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, rb_size_t(free)(void *))
|
|
{
|
|
free(rb->buffer);
|
|
}
|
|
|
|
enum WriteResult
|
|
rb_push(struct RingBuf *rb, void *data[], rb_size_t amount, MEMCPY_T)
|
|
{
|
|
if(rb->write_idx + amount >= rb->capacity) {
|
|
return CollisionError;
|
|
}
|
|
|
|
printf("write_idx: %d\n", rb->write_idx);
|
|
printf("amount: %d\n", amount);
|
|
|
|
for(rb_size_t i = 0; i < amount; i++) {
|
|
printf("memcpy: %d, write_idx: %d\n", i, rb->write_idx);
|
|
// write to the buffer
|
|
rb->buffer[rb->write_idx] = data[i];
|
|
// memcpy(rb->buffer + rb->write_idx * rb->struct_size, data[i], rb->struct_size);
|
|
|
|
rb->write_idx = (rb->write_idx + 1) % rb->capacity;
|
|
}
|
|
|
|
// Read it back to stdout
|
|
for(rb_size_t i = 0; i < amount; i++) {
|
|
printf("read_idx: %d\n", rb->read_idx);
|
|
printf("data: %d\n", *(int *)rb->buffer[rb->read_idx]);
|
|
rb->read_idx = (rb->read_idx + 1) % rb->capacity;
|
|
}
|
|
|
|
return Ok;
|
|
}
|