From 82de9a951b1a43c4abc71425be03877a43063584 Mon Sep 17 00:00:00 2001 From: Leonard Kugis Date: Wed, 15 May 2024 19:01:15 +0200 Subject: Added first version --- circular_buffer.h | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 circular_buffer.h (limited to 'circular_buffer.h') 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 + +/* +* 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 -- cgit v1.2.1