ringbuf/ringbuf.c

80 lines
2.1 KiB
C
Raw Normal View History

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
void
2024-06-27 14:06:08 +02:00
rb_init(struct RingBuf *rb, rb_size_t capacity, ALLOC_T malloc_fn,
rb_size_t struct_size)
2024-06-27 00:05:49 +02:00
{
2024-06-23 14:08:57 +02:00
rb->struct_size = struct_size;
rb->capacity = capacity;
rb->write_idx = 0;
rb->read_idx = 0;
2024-06-27 02:35:39 +02:00
rb->buffer = malloc_fn(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
2024-06-27 14:06:08 +02:00
rb_push(struct RingBuf *rb, void *data, rb_size_t amount, MEMCPY_T memcpy_fn)
2024-06-27 00:05:49 +02:00
{
2024-06-27 01:21:25 +02:00
printf("\nWriting %d elements\n", amount);
2024-06-27 14:06:08 +02:00
// We need to do this iteratively, since a memcpy of
// multiple elements may overshoot the buffer.
for(int i = 0; i < amount; i++) {
void *src = data + i * rb->struct_size; // One element
void *dest = rb->buffer + (rb->write_idx + i) * rb->struct_size;
printf("Destination: %p\n", dest);
printf("Buffer: %p\n", rb->buffer);
printf("struct_size: %d\n", rb->struct_size);
// For each byte in the struct, copy it over
for (int j = 0; j < rb->struct_size; j++) {
printf("Copying from %p to %p\n", src + j, dest + j);
printf("j: %d\n", j);
memcpy_fn(dest+j, src+j, 1);
}
// memcpy_fn(dest, src, rb->struct_size);
}
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);
2024-06-27 14:06:08 +02:00
for(int i = 0; i < amount; i++) {
}
}
void
print_seq(void *begin, int amount)
{
printf("\nPrinting sequence\n");
for(int i = 0; i < amount; i++) {
int *val = (int *)(begin + 4 * i);
printf("V: %d, A: %u\n", *val, val);
}
2024-06-27 01:21:25 +02:00
}