Skip to content
Snippets Groups Projects
Commit 47950e8b authored by René Kijewski's avatar René Kijewski
Browse files

ringbuffer: remove pointer to the end

There is no need for an explicit pointer to the end of the buffer.
parent 726af8d4
No related branches found
No related tags found
No related merge requests found
......@@ -21,10 +21,9 @@
typedef struct ringbuffer {
char *buf;
unsigned int start;
unsigned int end;
unsigned int size;
unsigned int avail;
unsigned int size;
unsigned int start;
unsigned int avail;
} ringbuffer_t;
void ringbuffer_init(ringbuffer_t *restrict rb, char *buffer, unsigned bufsize);
......
......@@ -12,6 +12,7 @@
* @{
* @file ringbuffer.c
* @author Kaspar Schleiser <kaspar@schleiser.de>
* @author René Kijewski <rene.kijewski@fu-berlin.de>
* @}
*/
......@@ -20,12 +21,29 @@
void ringbuffer_init(ringbuffer_t *restrict rb, char *buffer, unsigned bufsize)
{
rb->buf = buffer;
rb->start = 0;
rb->end = 0;
rb->size = bufsize;
rb->start = 0;
rb->avail = 0;
}
static void add_tail(ringbuffer_t *restrict rb, char c)
{
unsigned pos = rb->start + rb->avail++;
if (pos >= rb->size) {
pos -= rb->size;
}
rb->buf[pos] = c;
}
static char get_head(ringbuffer_t *restrict rb)
{
char result = rb->buf[rb->start];
if ((--rb->avail == 0) || (++rb->start == rb->size)) {
rb->start = 0;
}
return result;
}
void ringbuffer_add(ringbuffer_t *restrict rb, const char *buf, unsigned n)
{
for (unsigned i = 0; i < n; i++) {
......@@ -35,45 +53,32 @@ void ringbuffer_add(ringbuffer_t *restrict rb, const char *buf, unsigned n)
void ringbuffer_add_one(ringbuffer_t *restrict rb, char c)
{
if (rb->avail == rb->size) {
ringbuffer_get_one(rb);
}
rb->buf[rb->end++] = c;
if (rb->end >= rb->size) {
rb->end = 0;
if (ringbuffer_full(rb)) {
get_head(rb);
}
rb->avail++;
add_tail(rb, c);
}
int ringbuffer_get_one(ringbuffer_t *restrict rb)
{
if (rb->avail == 0) {
return -1;
if (!ringbuffer_empty(rb)) {
return (unsigned char) get_head(rb);
}
rb->avail--;
int c = (char)rb->buf[rb->start++];
if (rb->start >= rb->size) {
rb->start = 0;
else {
return -1;
}
return c;
}
unsigned ringbuffer_get(ringbuffer_t *restrict rb, char *buf, unsigned n)
{
unsigned count = 0;
while (rb->avail && (count < n)) {
buf[count++] = ringbuffer_get_one(rb);
if (n > rb->avail) {
n = rb->avail;
}
return count;
for (unsigned i = 0; i < n; ++i) {
buf[i] = get_head(rb);
}
return n;
}
int ringbuffer_peek_one(const ringbuffer_t *restrict rb_)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment