I searched the net for over two days to make a circular list that could be used for different data types. I use c language, so I mean I am looking for some code that can manage buffers with char, short, int, signed, or unsigned definitions. what I have found more useful is these 2 links
The problem I have is that I am working on embedded boards with an external ram and since I do have not enough memory inside the processor chip, I have to use external memory, and in this case, malloc function would not work correctly.
So I am looking for some code or enhancing the embedded artistry code to be flexible to different data types.
What I had done with no good result was to change this code into two parts. one for char type and one for short type.
struct circular_buf_t {
uint8_t *buffer;
size_t head;
size_t tail;
size_t max; // of the buffer
bool full;
};
struct circular_buf_short_t {
void *buffer;
size_t head;
size_t tail;
size_t max; // of the buffer
bool full;
};
cbuf_handle_t circular_buf_init(uint8_t *buffer, size_t size) {
cbuf_handle_t cbuf = malloc(sizeof(circular_buf_t));
cbuf->buffer = buffer;
cbuf->max = size;
circular_buf_reset(cbuf);
return cbuf;
}
cbuf_handle_short_t circular_buf_short_init(uint16_t *buffer, size_t size) {
cbuf_handle_short_t cbuf = malloc(sizeof(cbuf_handle_short_t));
circular_buf_short_reset(cbuf);
cbuf->buffer = buffer;
cbuf->max = size;
return cbuf;
}
int circular_buf_try_put(cbuf_handle_t me, uint8_t data) {
int r = -1;
if (!circular_buf_full(me)) {
me->buffer[me->head] = data;
advance_head_pointer(me);
r = 0;
}
return r;
}
int circular_buf_short_try_put(cbuf_handle_short_t me, uint16_t data) {
int r = -1;
if (!circular_buf_short_full(me)) {
me->buffer[me->head] = data;
advance_head_pointer_short(me);
r = 0;
}
return r;
}
For your purpose, you could use a generic circular buffer structure that you initialize with an array of the type needed (eg: 8, 16 or 32 bit integers) along with the element size and element count.
The ancillary functions work the same for all types, and the get and put functions handle the specific type with a test.
If you know the type of element for a given buffer, you can use the specific get/put function.
Here is a sample implementation: