avrinput/ringbuffer.c

60 lines
977 B
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)
{
return buffer->head != buffer->tail;
}
unsigned char
ringbuffer_get_char(ringbuffer_t buffer)
{
unsigned char result;
if(buffer->head == buffer->tail)
{
return 0;
}
result = buffer->buffer[buffer->tail];
buffer->tail = (buffer->tail + 1) % buffer->length;
return result;
}
int
ringbuffer_put_char(ringbuffer_t buffer
, unsigned char c)
{
buffer->ovf = 0;
buffer->buffer[buffer->head] = c;
buffer->head = (buffer->head + 1) % buffer->length;
if(buffer->head == buffer->tail)
{
buffer->ovf = 1;
}
return buffer->ovf;
}