summaryrefslogtreecommitdiff
path: root/cesar/lib/src/circular_buffer.c
diff options
context:
space:
mode:
Diffstat (limited to 'cesar/lib/src/circular_buffer.c')
-rw-r--r--cesar/lib/src/circular_buffer.c101
1 files changed, 101 insertions, 0 deletions
diff --git a/cesar/lib/src/circular_buffer.c b/cesar/lib/src/circular_buffer.c
new file mode 100644
index 0000000000..1f5a1851e9
--- /dev/null
+++ b/cesar/lib/src/circular_buffer.c
@@ -0,0 +1,101 @@
+/* Cesar project {{{
+ *
+ * Copyright (C) 2008 Spidcom
+ *
+ * <<<Licence>>>
+ *
+ * }}} */
+/**
+ * \file lib/src/circular_buffer.c
+ * \brief Circular buffer list.
+ * \ingroup lib
+ *
+ * Provides a circular buffer list API.
+ * Reserve the real size of the buffer just after the declaration of the
+ * circular buffer to not have some memory problems.
+ */
+#include "common/std.h"
+#include "lib/circular_buffer.h"
+
+/**
+ * Initialize the buffer address list
+ *
+ * \param list the buffer address list to initiliaze
+ * \param buffer the circular buffer to use.
+ * \param number_slots the quantity of slots.
+ */
+void
+circular_buffer_init (circular_buffer_t *list, void *buffer, uint number_slots)
+{
+ dbg_assert (list);
+
+ list->num_slots = number_slots;
+ list->buffer = buffer;
+ list->head = 0;
+ list->tail = 0;
+ list->nb_elements = 0;
+}
+
+/**
+ * Add an address to the buffer address buffer list
+ *
+ * \param ctx the ctx containing the list.
+ * \param address the address to add to the list
+ * \param number_of_slots the quantity of address it can keep in the list.
+ *
+ * \return true if the buffer had been added, false otherwise
+ */
+bool
+circular_buffer_add (circular_buffer_t *ctx, void *address)
+{
+ dbg_assert (ctx);
+
+ if (ctx->nb_elements < ctx->num_slots)
+ {
+ ctx->buffer[ctx->tail] = address;
+ ctx->tail ++;
+ ctx->nb_elements ++;
+ if (ctx->tail > ctx->num_slots - 1)
+ {
+ ctx->tail = 0;
+ }
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Peek the first element of the list without removing it.
+ *
+ * \param ctx the context.
+ */
+void*
+circular_buffer_peek (circular_buffer_t *ctx)
+{
+ return ctx->buffer[ctx->head];
+}
+
+/**
+ * Get the current address and go to the next one.
+ *
+ * \param ctx the ctx containing the list.
+ * \param number_of_slots the quantity of address it can keep in the list.
+ */
+void*
+circular_buffer_get (circular_buffer_t *ctx)
+{
+ void *buffer = NULL;
+
+ if (ctx->nb_elements != 0)
+ {
+ buffer = ctx->buffer[ctx->head];
+ ctx->head ++;
+ ctx->nb_elements --;
+ if (ctx->head > ctx->num_slots - 1)
+ {
+ ctx->head = 0;
+ }
+ }
+ return buffer;
+}
+