Files
HardwareAdapter/controller/ringbuffer.c

66 lines
1.7 KiB
C
Raw Normal View History

2025-05-20 22:23:19 +02:00
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
2025-05-21 22:39:32 +02:00
#include <stdio.h>
2025-05-20 22:23:19 +02:00
#include "ringbuffer.h"
void _ringBufferIncReader(struct ringBuffer *buf) {
2025-05-21 22:39:32 +02:00
buf->reader += buf->blockSize;
if (buf->reader >= buf->buffer + buf->blocks * buf->blockSize) {
buf->reader = buf->buffer;
2025-05-20 22:23:19 +02:00
}
}
void _ringBufferIncWriter(struct ringBuffer *buf) {
2025-05-21 22:39:32 +02:00
buf->writer += buf->blockSize;
if (buf->writer == buf->buffer + buf->blocks * buf->blockSize) {
buf->writer = buf->buffer;
2025-05-20 22:23:19 +02:00
}
if (buf->writer == buf->reader) {
// we incremented the writer and now it is equal to reader
// this means, the writer is overtaking the reader
// so push the reader forward, even if we are
// loosing data but this is how ring buffers work, eh?
_ringBufferIncReader(buf);
}
}
2025-05-21 22:39:32 +02:00
void ringBufferCreate(int blocks, size_t blockSize, struct ringBuffer *out) {
out->buffer = malloc(blocks * blockSize);
2025-05-21 22:39:32 +02:00
out->blocks = blocks;
out->blockSize = blockSize;
out->reader = out->buffer;
out->writer = out->buffer;
pthread_mutex_init(&out->mutex, NULL);
2025-05-20 22:23:19 +02:00
}
void ringBufferDestroy(struct ringBuffer *buf) {
free(buf->buffer);
pthread_mutex_destroy(&buf->mutex);
2025-05-20 22:23:19 +02:00
}
int ringBufferRead(struct ringBuffer *buf, void *out) {
pthread_mutex_lock(&buf->mutex);
2025-05-20 22:23:19 +02:00
if (buf->reader != buf->writer) {
// we have data to read
memcpy(out, buf->reader, buf->blockSize);
2025-05-20 22:23:19 +02:00
_ringBufferIncReader(buf);
pthread_mutex_unlock(&buf->mutex);
2025-05-20 22:23:19 +02:00
return 0;
} else {
// nothing to read
pthread_mutex_unlock(&buf->mutex);
2025-05-20 22:23:19 +02:00
return 1;
}
}
void ringBufferWrite(struct ringBuffer *buf, void *in) {
pthread_mutex_lock(&buf->mutex);
memcpy(buf->writer, in, buf->blockSize);
2025-05-20 22:23:19 +02:00
_ringBufferIncWriter(buf);
pthread_mutex_unlock(&buf->mutex);
2025-05-20 22:23:19 +02:00
}