Alejandro Giraldo Martinez / Buffer

Files at this revision

API Documentation at this revision

Comitter:
alejo5214416
Date:
Sat Jul 28 01:29:23 2018 +0000
Commit message:
Comunicacion maestro esclavo con confirmacion de 1S 1Y 1N para solicitudes y respuestas;

Changed in this revision

Buffer.cpp Show annotated file Show diff for this revision Revisions of this file
Buffer.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 72ef8c56fea0 Buffer.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Buffer.cpp	Sat Jul 28 01:29:23 2018 +0000
@@ -0,0 +1,63 @@
+#include "Buffer.h"
+#include "mbed.h"
+
+int circular_buf_reset(circular_buf_t * cbuf)
+{
+    int r = -1;
+
+    if(cbuf) {
+        cbuf->head = 0;
+        cbuf->tail = 0;
+        cbuf->size = 0;
+        r = 0;
+    }
+
+    return r;
+
+}
+
+bool circular_buf_empty(circular_buf_t cbuf)
+{
+    // We define empty as head == tail
+    return (cbuf.head == cbuf.tail);
+}
+
+bool circular_buf_full(circular_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 circular_buf_put(circular_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 circular_buf_get(circular_buf_t * cbuf, uint8_t * data)
+{
+    int r = -1;
+
+    if(cbuf && data && !circular_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
diff -r 000000000000 -r 72ef8c56fea0 Buffer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Buffer.h	Sat Jul 28 01:29:23 2018 +0000
@@ -0,0 +1,19 @@
+#include "mbed.h"
+
+#ifndef BUFFER_H
+#define BUFFER_H
+
+typedef struct {
+    uint8_t * buffer;
+    size_t head;
+    size_t tail;
+    size_t size; //of the buffer
+} circular_buf_t;
+
+int circular_buf_reset(circular_buf_t * cbuf);
+int circular_buf_put(circular_buf_t * cbuf, uint8_t data);
+int circular_buf_get(circular_buf_t * cbuf, uint8_t* data);
+bool circular_buf_empty(circular_buf_t cbuf);
+bool circular_buf_full(circular_buf_t cbuf);
+
+#endif
\ No newline at end of file