Ringbuffer: add null checks and more const

This commit is contained in:
Midgard 2020-02-01 23:13:50 +01:00
parent 269a45839c
commit 3fb475dc70
Signed by: midgard
GPG key ID: 511C112F1331BBB4

View file

@ -4,7 +4,21 @@
#include "ringbuffer.h"
#include "../memory.c"
struct ringbuffer* rbfr_create(const int capacity, void (*destroy_element)(void*)) {
#define ERROR(msg) \
do { \
/* TODO Do something error-ish */ \
} while(0)
#define ASSERT_NONNULL_ARG(argument) { \
if (argument == NULL) { \
ERROR(__func__ " got NULL for argument '" #argument "'"); \
} \
}
struct ringbuffer* rbfr_create(const int capacity, void (*const destroy_element)(void*)) {
ASSERT_NONNULL_ARG(destroy_element);
struct ringbuffer* const this = alloc(sizeof (struct ringbuffer));
this->buffer = alloc(capacity * sizeof (void*));
@ -17,21 +31,31 @@ struct ringbuffer* rbfr_create(const int capacity, void (*destroy_element)(void*
return this;
}
void rbfr_destroy(struct ringbuffer* this) {
void rbfr_destroy(struct ringbuffer* const this) {
ASSERT_NONNULL_ARG(this);
rbfr_clear(this);
free(this->buffer);
this->buffer = NULL;
free(this);
}
int rbfr_size(const struct ringbuffer* this) {
int rbfr_size(const struct ringbuffer* const this) {
ASSERT_NONNULL_ARG(this);
return this->size;
}
int rbfr_capacity(const struct ringbuffer* this) {
ASSERT_NONNULL_ARG(this);
return this->buffer_n;
}
void rbfr_enqueue(struct ringbuffer* this, void* element) {
void rbfr_enqueue(struct ringbuffer* this, void* const element) {
ASSERT_NONNULL_ARG(this);
if (this->buffer_n == 0) {
return;
}
@ -49,7 +73,10 @@ void rbfr_enqueue(struct ringbuffer* this, void* element) {
return;
}
bool rbfr_peek(const struct ringbuffer* this, void** element) {
bool rbfr_peek(const struct ringbuffer *const this, void** element) {
ASSERT_NONNULL_ARG(this);
ASSERT_NONNULL_ARG(element);
if (this->size == 0) {
return false;
}
@ -57,7 +84,10 @@ bool rbfr_peek(const struct ringbuffer* this, void** element) {
return true;
}
bool rbfr_dequeue(struct ringbuffer* this, void** element) {
bool rbfr_dequeue(struct ringbuffer *const this, void** element) {
ASSERT_NONNULL_ARG(this);
ASSERT_NONNULL_ARG(element);
if (!rbfr_peek(this, element)) {
return false;
}
@ -70,6 +100,8 @@ bool rbfr_dequeue(struct ringbuffer* this, void** element) {
}
void rbfr_clear(struct ringbuffer* this) {
ASSERT_NONNULL_ARG(this);
void* element;
while (rbfr_dequeue(this, &element)) {
this->destroy_element(element);