aboutsummaryrefslogtreecommitdiff
path: root/circular_buffer.h
diff options
context:
space:
mode:
Diffstat (limited to 'circular_buffer.h')
-rw-r--r--circular_buffer.h82
1 files changed, 82 insertions, 0 deletions
diff --git a/circular_buffer.h b/circular_buffer.h
new file mode 100644
index 0000000..a12bbbc
--- /dev/null
+++ b/circular_buffer.h
@@ -0,0 +1,82 @@
+/*
+ * ------------------------------------------------------------
+ * "THE BEERWARE LICENSE" (Revision 42):
+ * diegohamilton26@gmail.com wrote this code. As long as you retain this
+ * notice, you can do whatever you want with this stuff. If we
+ * meet someday, and you think this stuff is worth it, you can
+ * buy me a beer in return,
+ * Diego Hamilton.
+ * ------------------------------------------------------------
+ */
+
+#ifndef _CIRCULAR_BUFFER_H
+#define _CIRCULAR_BUFFER_H
+
+#include <stddef.h>
+
+/*
+* BUF must be a pointer of any buffer with type 'NAME' defined.
+* ELEM must be a element (NOT A POINTER) of type T defined.
+*/
+
+#define circular_buffer_struct(T, SIZE) \
+ struct { \
+ size_t occup; \
+ size_t size; \
+ size_t head, tail; \
+ T data[SIZE]; \
+ }
+
+#define cb_init(BUF, SIZE) \
+ do { \
+ (BUF).size = SIZE; \
+ (BUF).occup = 0; \
+ (BUF).head = 0; \
+ (BUF).tail = 0; \
+ } while(0)
+
+#define cb_size(BUF) ((BUF).size)
+#define cb_full(BUF) ((BUF).occup == (BUF).size)
+#define cb_empty(BUF) ((BUF).occup == 0)
+#define cb_occupation(BUF) ((BUF).occup)
+#define cb_reset(BUF) \
+ do { \
+ (BUF).head = 0; \
+ (BUF).tail = 0; \
+ (BUF).occup = 0; \
+ } while(0)
+
+/* TODO: replace occup by calculations w/ head and tail? */
+#define cb_push(BUF, ELEM) \
+ do { \
+ ((BUF).data)[(BUF).tail] = (ELEM); \
+ if ((BUF).tail == cb_size(BUF) - 1) { \
+ (BUF).tail = 0; \
+ } else { \
+ (BUF).tail = ((BUF).tail + 1); \
+ } \
+ if (cb_full((BUF))) { \
+ if ((BUF).head == cb_size(BUF) - 1) { \
+ (BUF).head = 0; \
+ } else { \
+ (BUF).head = ((BUF).head + 1); \
+ } \
+ } else { \
+ (BUF).occup = (BUF).occup + 1; \
+ } \
+ } while(0)
+
+#define cb_pop(BUF, ELEM) \
+ do { \
+ if(!cb_empty((BUF))) { \
+ (ELEM) = (BUF).data[(BUF).head]; \
+ if ((BUF).head == cb_size(BUF) - 1) { \
+ (BUF).head = 0; \
+ } else { \
+ (BUF).head = ((BUF).head + 1); \
+ } \
+ (BUF).occup -= 1; \
+ } \
+ } while(0)
+
+#endif