diff --git a/driver.c b/driver.c index 57d0b44..d80ceed 100644 --- a/driver.c +++ b/driver.c @@ -13,8 +13,8 @@ main(void) struct RingBuf rb; rb_init(&rb, 10, malloc, sizeof(int)); - int data[] = { 1, 2, 3, 4, 5 }; - rb_push(&rb, (void **)data, 5, memcpy); + int data[] = { 5, 6, 7, 8 }; + rb_push(&rb, (void *)data, 4, memcpy); int dest[5]; rb_read(&rb, (void *)dest, 5); diff --git a/ringbuf.c b/ringbuf.c index fa93c4c..64f65e4 100644 --- a/ringbuf.c +++ b/ringbuf.c @@ -6,17 +6,14 @@ #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_init(struct RingBuf *rb, rb_size_t capacity, ALLOC_T malloc_fn, 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? */ + rb->buffer = malloc_fn(capacity * struct_size); /* Calloc? */ // Read from buffer at max position to force a segfault if theres an issue printf("Reading from buffer at position %d\n", @@ -35,20 +32,9 @@ rb_destroy(struct RingBuf *rb, void(free)()) } enum WriteResult -rb_push(struct RingBuf *rb, void *data[], rb_size_t amount, MEMCPY_T) +rb_push(struct RingBuf *rb, void *data[], rb_size_t amount, MEMCPY_T memcpy_fn) { printf("\nWriting %d elements\n", amount); - for(rb_size_t i = 0; i < amount; i++) { - // printf("Index: %d\n", rb->write_idx); - int position = (rb->write_idx + i) % rb->capacity; - int offset = position * rb->struct_size; - printf("Position: %d\n", position); - printf("Offset: %d\n", offset); - memcpy(rb->buffer + offset, data + offset, rb->struct_size); - - printf("Data at location %d: %d\n", position, *(int *)(rb->buffer + offset)); - } - return Ok; } @@ -56,11 +42,5 @@ void rb_read(struct RingBuf *rb, void *dest, int amount) { printf("\nReading %d elements\n", amount); - for (int i = 0; i < amount; i++) { - int position = (rb->read_idx + i) % rb->capacity; - int offset = position * rb->struct_size; - printf("Position: %d\n", position); - printf("Offset: %d\n", offset); - memcpy(dest + offset, rb->buffer + offset, rb->struct_size); - } + for(int i = 0; i < amount; i++) { } } diff --git a/ringbuf.h b/ringbuf.h index a8c52d8..8be1026 100644 --- a/ringbuf.h +++ b/ringbuf.h @@ -6,12 +6,17 @@ #define rb_size_t int #endif +/** Signatures of generic functions */ +typedef void *(*ALLOC_T)(rb_size_t); +typedef void *(*MEMCPY_T)(void *, const void *, rb_size_t); + /** * Ring buffer, also known as circular buffer. */ struct RingBuf { rb_size_t struct_size; /* Size of the struct */ rb_size_t capacity; /* The physical capacity of the entire ringbuf */ + rb_size_t size; /* The current size of the ring buffer */ rb_size_t write_idx; /* The write head */ rb_size_t read_idx; /* THe read head */ void **buffer; /* The actual data */