2024-06-23 14:08:57 +02:00
|
|
|
/* SPDX-License-Identifier: MIT */
|
|
|
|
|
2024-06-27 00:05:49 +02:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
2024-06-23 14:08:57 +02:00
|
|
|
#include "ringbuf.h"
|
|
|
|
|
2024-06-27 00:05:49 +02:00
|
|
|
#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)
|
|
|
|
{
|
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-27 01:21:25 +02:00
|
|
|
|
|
|
|
// 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);
|
2024-06-23 14:08:57 +02:00
|
|
|
}
|
|
|
|
|
2024-06-27 00:05:49 +02:00
|
|
|
void
|
2024-06-27 01:21:25 +02:00
|
|
|
rb_destroy(struct RingBuf *rb, void(free)())
|
2024-06-27 00:05:49 +02:00
|
|
|
{
|
2024-06-23 16:27:51 +02:00
|
|
|
free(rb->buffer);
|
|
|
|
}
|
2024-06-23 14:08:57 +02:00
|
|
|
|
2024-06-27 00:05:49 +02:00
|
|
|
enum WriteResult
|
|
|
|
rb_push(struct RingBuf *rb, void *data[], rb_size_t amount, MEMCPY_T)
|
|
|
|
{
|
2024-06-27 01:21:25 +02:00
|
|
|
printf("\nWriting %d elements\n", amount);
|
2024-06-27 00:05:49 +02:00
|
|
|
for(rb_size_t i = 0; i < amount; i++) {
|
2024-06-27 01:21:25 +02:00
|
|
|
// 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);
|
2024-06-27 00:05:49 +02:00
|
|
|
|
2024-06-27 01:21:25 +02:00
|
|
|
printf("Data at location %d: %d\n", position, *(int *)(rb->buffer + offset));
|
2024-06-27 00:05:49 +02:00
|
|
|
}
|
|
|
|
|
2024-06-23 14:08:57 +02:00
|
|
|
return Ok;
|
2024-06-27 00:05:49 +02:00
|
|
|
}
|
2024-06-27 01:21:25 +02:00
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|