avrinput/ringbuffer.c

77 lines
1.3 KiB
C
Raw Normal View History

2019-01-01 15:48:54 +00:00
#include "ringbuffer.h"
#include <stdlib.h>
ringbuffer_t
ringbuffer_new(size_t size)
{
ringbuffer_t buffer = malloc(sizeof(struct ringbuffer_s));
if(!buffer)
{
return NULL;
}
buffer->buffer = malloc(sizeof(char) * size);
if(!buffer->buffer)
{
free(buffer);
return NULL;
}
buffer->length = size;
buffer->head = 0;
buffer->tail = 0;
buffer->ovf = 0;
return buffer;
}
int
ringbuffer_nonempty(ringbuffer_t buffer)
{
2019-04-07 18:35:05 +00:00
return (buffer->head != buffer->tail) || buffer->ovf;
2019-01-01 15:48:54 +00:00
}
unsigned char
ringbuffer_get_char(ringbuffer_t buffer)
{
unsigned char result;
2019-04-07 18:35:05 +00:00
if((buffer->head == buffer->tail) && !buffer->ovf)
2019-01-01 15:48:54 +00:00
{
return 0;
}
2019-04-07 18:35:05 +00:00
buffer->ovf = 0;
2019-01-01 15:48:54 +00:00
result = buffer->buffer[buffer->tail];
buffer->tail = (buffer->tail + 1) % buffer->length;
return result;
}
int
ringbuffer_put_char(ringbuffer_t buffer
, unsigned char c)
{
2019-04-07 18:35:05 +00:00
if(buffer->ovf)
{
return 1;
}
2019-01-01 15:48:54 +00:00
buffer->buffer[buffer->head] = c;
buffer->head = (buffer->head + 1) % buffer->length;
if(buffer->head == buffer->tail)
{
buffer->ovf = 1;
}
2019-04-07 18:35:05 +00:00
return 0;
2019-01-01 15:48:54 +00:00
}
2019-04-07 18:35:05 +00:00
size_t ringbuffer_empty_bytes(ringbuffer_t buffer)
{
if(buffer->ovf)
{
return 0;
}
int raw_empty = buffer->length - (buffer->head - buffer->tail);
if(raw_empty > buffer->length)
{
return raw_empty - buffer->length;
}
return raw_empty;
}