#include "ringbuffer.h" #include 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) || buffer->ovf; } unsigned char ringbuffer_get_char(ringbuffer_t buffer) { unsigned char result; if((buffer->head == buffer->tail) && !buffer->ovf) { return 0; } buffer->ovf = 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) { if(buffer->ovf) { return 1; } buffer->buffer[buffer->head] = c; buffer->head = (buffer->head + 1) % buffer->length; if(buffer->head == buffer->tail) { buffer->ovf = 1; } return 0; } 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; }