Skip to content

Instantly share code, notes, and snippets.

@dpc
Last active August 29, 2015 14:23
Show Gist options
  • Save dpc/a194b7784adfa150a450 to your computer and use it in GitHub Desktop.
Save dpc/a194b7784adfa150a450 to your computer and use it in GitHub Desktop.
cbuf
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "cbuf.h"
uint8_t buf[16];
int main() {
struct cbuf cbuf;
size_t cur_len = 0;
uint8_t put_val = 0;
uint8_t get_val = 0;
cbuf_init(&cbuf, buf, sizeof buf);
while (true) {
if (cur_len == 0) {
assert(cbuf_is_empty(&cbuf));
}
if (cur_len == sizeof buf) {
assert(cbuf_is_full(&cbuf));
}
if (rand() & 1) {
if (!cbuf_is_empty(&cbuf)) {
uint8_t val = cbuf_get(&cbuf);
assert(val == get_val++);
cur_len--;
printf("%u len: %u\n",
(unsigned)val, (unsigned)
cur_len);
}
} else {
if (!cbuf_is_full(&cbuf)) {
cbuf_put(&cbuf, put_val++);
cur_len++;
}
}
}
return 0;
}
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
/* TODO: Fix on 64 architecture */
#define CBUF_DATA_BIT (1 << 31)
/**
* Char circular buffer
*/
struct cbuf {
uint8_t *data;
size_t size;
size_t start;
size_t end;
};
static inline
bool cbuf_is_empty(struct cbuf* cbuf)
{
return cbuf->start == cbuf->end;
}
static inline
bool cbuf_is_full(struct cbuf* cbuf)
{
return (cbuf->start ^ cbuf->end) == CBUF_DATA_BIT;
}
static inline
uint8_t cbuf_get(struct cbuf* cbuf)
{
uint8_t ret = cbuf->data[cbuf->start & ~CBUF_DATA_BIT];
cbuf->start++;
if ((cbuf->start & ~CBUF_DATA_BIT) >= cbuf->size) {
cbuf->start -= cbuf->size;
cbuf->start ^= CBUF_DATA_BIT;
}
return ret;
}
static inline
void cbuf_put(struct cbuf* cbuf, uint8_t byte)
{
cbuf->data[cbuf->end & ~CBUF_DATA_BIT] = byte;
cbuf->end++;
if ((cbuf->end & ~CBUF_DATA_BIT) >= cbuf->size) {
cbuf->end -= cbuf->size;
cbuf->end ^= CBUF_DATA_BIT;
}
}
static inline
void cbuf_init(struct cbuf* cbuf, uint8_t* data, size_t size)
{
memset(cbuf, 0, sizeof(*cbuf));
cbuf->data = data;
cbuf->size = size;
}
cbuf: cbuf.h cbuf.c
gcc -O3 -std=gnu99 cbuf.c -o cbuf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment