diff --git a/cbuffer/circular_buffer.c b/cbuffer/circular_buffer.c new file mode 100644 index 0000000..9078537 --- /dev/null +++ b/cbuffer/circular_buffer.c @@ -0,0 +1,62 @@ +#include +#include "stdint.h" +#include "circular_buffer.h" + +CB_StatusTypeDef cb_init(CB_TypeDef *cb, void *buffer, uint16_t capacity, uint8_t item_size) +{ + if (buffer == NULL || cb == NULL) + { + return CB_ERROR; + } + + cb->buffer = buffer; + cb->buffer_end = (uint8_t *)cb->buffer + capacity * item_size; + cb->capacity = capacity; + cb->count = 0; + cb->item_size = item_size; + cb->head = cb->buffer; + cb->tail = cb->buffer; + + return CB_OK; +} + +CB_StatusTypeDef cb_push_back(CB_TypeDef *cb, const void *item) +{ + if (cb == NULL) + { + return CB_ERROR; + } + + if (cb->count == cb->capacity) + { + return CB_FULL; + } + memcpy(cb->head, item, cb->item_size); + cb->head = (uint8_t *)cb->head + cb->item_size; + if (cb->head == cb->buffer_end) + cb->head = cb->buffer; + cb->count++; + + return CB_OK; +} + +CB_StatusTypeDef cb_pop_front(CB_TypeDef *cb, void *item) +{ + if (cb == NULL) + { + return CB_ERROR; + } + + if (cb->count == 0) + { + return CB_EMPTY; + } + + memcpy(item, cb->tail, cb->item_size); + cb->tail = (uint8_t *)cb->tail + cb->item_size; + if (cb->tail == cb->buffer_end) + cb->tail = cb->buffer; + cb->count--; + + return CB_OK; +} \ No newline at end of file diff --git a/cbuffer/circular_buffer.h b/cbuffer/circular_buffer.h new file mode 100644 index 0000000..43f68e2 --- /dev/null +++ b/cbuffer/circular_buffer.h @@ -0,0 +1,37 @@ +#ifndef __CIRCULAT_BUFFER__ +#define __CIRCULAT_BUFFER__ + +#ifdef __cplusplus +extern "C" +{ +#endif +#include + + typedef enum + { + CB_OK = 0x00, + CB_ERROR = -0x01, + CB_EMPTY = -0x02, + CB_FULL = -0x03 + } CB_StatusTypeDef; + + typedef struct + { + void *buffer; // data buffer + void *buffer_end; // end of data buffer + uint16_t capacity; // maximum number of items in the buffer + uint16_t count; // number of items in the buffer + uint8_t item_size; // size of each item in the buffer + void *head; // pointer to head + void *tail; // pointer to tail + } CB_TypeDef; + + CB_StatusTypeDef cb_init(CB_TypeDef *cb, void *buffer, uint16_t capacity, uint8_t item_size); + CB_StatusTypeDef cb_push_back(CB_TypeDef *cb, const void *item); + CB_StatusTypeDef cb_pop_front(CB_TypeDef *cb, void *item); + +#ifdef __cplusplus +} +#endif + +#endif /* __CIRCULAT_BUFFER__ */ \ No newline at end of file