From 3fb475dc701b7cb6adcc92a6c088ca394bb72216 Mon Sep 17 00:00:00 2001 From: Midgard Date: Sat, 1 Feb 2020 23:13:50 +0100 Subject: [PATCH] Ringbuffer: add null checks and more const --- kernel/util/ringbuffer.c | 44 ++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/kernel/util/ringbuffer.c b/kernel/util/ringbuffer.c index c1031c5..aa631a1 100644 --- a/kernel/util/ringbuffer.c +++ b/kernel/util/ringbuffer.c @@ -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);