Skip to content

Instantly share code, notes, and snippets.

@jstimpfle
Last active September 16, 2020 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstimpfle/69414d81c4a7a741c3b00c67984c2d68 to your computer and use it in GitHub Desktop.
Save jstimpfle/69414d81c4a7a741c3b00c67984c2d68 to your computer and use it in GitHub Desktop.
/*
Ringbuffers are surprisingly hard to code because wraparound
can split the readable / writeable region in two. This is the
cutest implementation that I've come up with so far.
NOT ACTUALLY TESTED
- jstimpfle, 2020-09
*/
struct Ringbuffer {
char *buffer;
int capacity;
int start;
int fill;
};
int ringbuffer_read_bytes(struct Ringbuffer *rb, void *data, int size)
{
if (size > rb->fill)
size = rb->fill;
int start = rb->start;
int end = rb->start + size;
int n = (end >= rb->capacity ? rb->capacity : end) - start;
memcpy(data, rb->buffer + start, n);
memcpy((char *)data + n, rb->buffer, size - n);
rb->start = end - (end >= rb->capacity ? rb->capacity : 0);
rb->fill -= size;
return size;
}
int ringbuffer_write_bytes(struct Ringbuffer *rb, const void *data, int size)
{
if (size > rb->capacity - rb->fill)
size = rb->capacity - rb->fill;
int start = rb->start + rb->fill;
if (start >= rb->capacity)
start -= rb->capacity;
int end = start + size;
int n = (end >= rb->capacity ? rb->capacity : end) - start;
memcpy(rb->buffer + start, data, n);
memcpy(rb->buffer, (char *)data + n, size - n);
rb->fill += size;
return size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment