Circular Buffer C implementation, must create a buffer structure instance in your main and then dinamically allocate memory for the buffer array.

Dependents:   Chat buffprob

Files at this revision

API Documentation at this revision

Comitter:
ivaariasga
Date:
Fri May 17 13:06:31 2019 +0000
Commit message:
Circular Buffer C implementation, must create an instance of the buffer structure and then allocate memory dinamically for the buffer.

Changed in this revision

circularBuff.cpp Show annotated file Show diff for this revision Revisions of this file
circularBuff.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/circularBuff.cpp	Fri May 17 13:06:31 2019 +0000
@@ -0,0 +1,64 @@
+#include "circularBuff.h"
+
+int circ_buf_rst(circ_buf_t * cbuf) 
+{
+    int r = -1;
+
+    if(cbuf)
+    {
+        cbuf->head = 0;
+        cbuf->tail = 0;
+        r = 0;
+    }
+
+    return r;
+}
+
+bool circ_buf_empty(circ_buf_t cbuf)
+{
+    // We define empty as head == tail
+    return (cbuf.head == cbuf.tail);
+}
+
+bool circ_buf_full(circ_buf_t cbuf)
+{
+    // We determine "full" case by head being one position behind the tail
+    // Note that this means we are wasting one space in the buffer!
+    // Instead, you could have an "empty" flag and determine buffer full that way
+    return ((cbuf.head + 1) % cbuf.size) == cbuf.tail;
+}
+
+int circ_buf_put(circ_buf_t * cbuf, uint8_t data)
+{
+    int r = -1;
+
+    if(cbuf)
+    {
+        cbuf->buffer[cbuf->head] = data;
+        cbuf->head = (cbuf->head + 1) % cbuf->size;
+
+        if(cbuf->head == cbuf->tail)
+        {
+            cbuf->tail = (cbuf->tail + 1) % cbuf->size;
+        }
+
+        r = 0;
+    }
+
+    return r;
+}
+
+int circ_buf_get(circ_buf_t * cbuf, uint8_t * data)
+{
+    int r = -1;
+
+    if(cbuf && data && !circ_buf_empty(*cbuf))
+    {
+        *data = cbuf->buffer[cbuf->tail];
+        cbuf->tail = (cbuf->tail + 1) % cbuf->size;
+
+        r = 0;
+    }
+
+    return r;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/circularBuff.h	Fri May 17 13:06:31 2019 +0000
@@ -0,0 +1,19 @@
+#include "mbed.h"
+
+#ifndef CIRCULARBUFF_H
+#define CIRCULARBUF_H
+
+typedef struct {
+    uint8_t *buffer;
+    size_t head;
+    size_t tail;
+    size_t size; //of the buffer
+} circ_buf_t;
+
+int circ_buf_rst(circ_buf_t * cbuf);
+int circ_buf_put(circ_buf_t * cbuf, uint8_t data);
+int circ_buf_get(circ_buf_t * cbuf, uint8_t * data);
+bool circ_buf_empty(circ_buf_t cbuf);
+bool circ_buf_full(circ_buf_t cbuf);
+
+#endif
\ No newline at end of file