/* SPDX-License-Identifier: MIT */ #include #include #include #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? */ // Read from buffer at max position to force a segfault if theres an issue printf("Reading from buffer at position %d\n", rb->capacity * rb->struct_size); void *top = rb->buffer[rb->capacity * rb->struct_size]; printf("Buffer top successfully read at virtual address: %p\n", &top); printf("Initialized ring buffer. Capacit: %d, struct_size: %d, total: %d\n", rb->capacity, rb->struct_size, rb->capacity * rb->struct_size); } void rb_destroy(struct RingBuf *rb, void(free)()) { free(rb->buffer); } enum WriteResult rb_push(struct RingBuf *rb, void *data[], rb_size_t amount, MEMCPY_T) { 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; } 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); } }