Skip to content

Instantly share code, notes, and snippets.

@mojtabacazi
Last active August 29, 2015 14:22
Show Gist options
  • Save mojtabacazi/dfa7c9b22cedd1c75f67 to your computer and use it in GitHub Desktop.
Save mojtabacazi/dfa7c9b22cedd1c75f67 to your computer and use it in GitHub Desktop.
Circular Buffer in C
/*
Source: http://stackoverflow.com/a/14047028/1017340
*/
#define BUFSIZE 128
char buf[BUFSIZE];
char *pIn, *pOut, *pEnd;
char full;
// init
void buf_init()
{
pIn = pOut = buf; // init to any slot in buffer
pEnd = &buf[BUFSIZE]; // past last valid slot in buffer
full = 0; // buffer is empty
}
// add char 'c' to buffer
int buf_put(char c)
{
if (pIn == pOut && full)
return 0; // buffer overrun
*pIn++ = c; // insert c into buffer
if (pIn >= pEnd) // end of circular buffer?
pIn = buf; // wrap around
if (pIn == pOut) // did we run into the output ptr?
full = 1; // can't add any more data into buffer
return 1; // all OK
}
// get a char from circular buffer
int buf_get(char *pc)
{
if (pIn == pOut && !full)
return 0; // buffer empty FAIL
*pc = *pOut++; // pick up next char to be returned
if (pOut >= pEnd) // end of circular buffer?
pOut = buf; // wrap around
full = 0; // there is at least 1 slot
return 1; // *pc has the data to be returned
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment