Skip to content

Instantly share code, notes, and snippets.

@PeterWaIIace
Last active October 28, 2022 20:52
Show Gist options
  • Save PeterWaIIace/de03f971e0d638602959d9cab170c810 to your computer and use it in GitHub Desktop.
Save PeterWaIIace/de03f971e0d638602959d9cab170c810 to your computer and use it in GitHub Desktop.
Experiment with generic ring buffer using preprocessor
#ifndef _RING_BUFFER_H_
#define _RING_BUFFER_H_
#include <stdint.h>
#define RING_BUFFER_MAX_SIZE 255
#define INIT_RING_BUFFER(_NAME,_SIZE,_DATATYPE,NULLTYPE)\
typedef struct _NAME ## _s_ring_buffer _NAME ## _s_ring_buffer;\
typedef struct _NAME ## _s_ring_buffer\
{\
_DATATYPE buffer[RING_BUFFER_MAX_SIZE];\
uint32_t size;\
uint32_t tail;\
uint32_t head;\
};\
typedef _NAME ## _s_ring_buffer _NAME ## _t_ring_buffer;\
_NAME ## _t_ring_buffer _NAME= {.size = _SIZE % RING_BUFFER_MAX_SIZE}; \
void _NAME ## _put_char(_DATATYPE c, _NAME ## _t_ring_buffer *rb)\
{\
rb->buffer[rb->head] = c;\
if(rb->head < rb->tail && rb->tail - rb->head == 1)\
{\
rb->tail++;\
rb->tail = rb->tail % rb->size;\
}\
rb->head++;\
rb->head = rb->head % rb->size;\
}\
uint16_t _NAME ## _get_length(_NAME ## _t_ring_buffer *rb)\
{\
if(rb->head < rb->tail)\
{\
return rb->head + (rb->size - rb->tail);\
}\
else\
{\
return rb->head - rb->tail;\
}\
}\
_DATATYPE _NAME ## _read_char(_NAME ## _t_ring_buffer *rb)\
{\
if(rb->tail != rb->head)\
{\
_DATATYPE ret_char = rb->buffer[rb->tail];\
rb->tail++;\
rb->tail = rb->tail % rb->size;\
return ret_char;\
}\
return NULLTYPE;\
}
#endif // _RING_BUFFER_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment