Skip to content

Instantly share code, notes, and snippets.

@jerrylogansquare
Created February 16, 2026 22:54
Show Gist options
  • Select an option

  • Save jerrylogansquare/8c58331bf94e3acd94db07dc643c0d2c to your computer and use it in GitHub Desktop.

Select an option

Save jerrylogansquare/8c58331bf94e3acd94db07dc643c0d2c to your computer and use it in GitHub Desktop.
b/**
* @file circbuff.c
* @brief A circular byte buffer implemtation optimized for UART interfaces.
* Please note design for multiple instances of circular buffers.
*
*
*/
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "util/circbuff.h"
#include "mcu_assert.h"
void circ_buf_init(CIRCBUFF_T *c, uint8_t * const buffer, int pow2_size )
{
assert_param (buffer != NULL);
// check if number is a power of 2
// e.g. 0x100 & 0x0FF = 0 OK , 0x120 & 0x11F = 0x100 assert
assert_param (!(pow2_size & (pow2_size - 1)));
c->buffer = buffer;
c->pow2_size = pow2_size;
c->head = 0;
c->tail = 0;
return ;
}
inline int circ_buf_push(CIRCBUFF_T *c, uint8_t data)
{
int retval = 0;
// check if already full first
if ( ((c->head+1) & (c->pow2_size-1)) == c->tail ) {
// sorry, already full
retval = -1;
}
else {
// go ahead a write next
c->buffer[c->head] = data;
// increment head, with wrap around
c->head = (c->head+1) & (c->pow2_size-1);
if ( (retval = (c->head - c->tail)) <= 0 ) {
retval = c->pow2_size - c->tail + c->head;
}
}
return retval;
}
inline int circ_buf_pop(CIRCBUFF_T *c, uint8_t *data)
{
int retval = 0;
if ( c->tail == c->head ) {
retval = 1;
*data = 0;
}
else {
*data = c->buffer[c->tail];
// increment tail pointer with size mask
c->tail = (c->tail+1) & (c->pow2_size-1);
}
return retval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment