You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

87 lines
2.0 KiB

#include "ringbuffer.h"
#include <stdio.h>
#include <stdlib.h>
struct ringbuffer_instance_t {
int32_t wr_pos;
int32_t rd_pos;
uint8_t *data;
uint32_t capacity;
bool full;
};
ringbuffer_t ringbuffer_create(uint32_t capacity)
{
ringbuffer_t inst = calloc(1, sizeof(struct ringbuffer_instance_t));
inst->data = calloc(capacity, sizeof(uint8_t));
inst->capacity = capacity;
inst->wr_pos = 0;
inst->rd_pos = 0;
inst->full = capacity == 0;
return inst;
}
uint32_t ringbuffer_capacity(ringbuffer_t instance)
{
return instance->capacity;
}
uint32_t ringbuffer_used(ringbuffer_t instance)
{
if (instance->full)
return instance->capacity;
return (instance->wr_pos - instance->rd_pos) % instance->capacity;
}
bool ringbuffer_empty(ringbuffer_t instance)
{
return (!instance->full && (instance->wr_pos == instance->rd_pos));
}
bool ringbuffer_full(ringbuffer_t instance)
{
return instance->full;
}
bool ringbuffer_enqueue(ringbuffer_t instance, uint8_t item)
{
if (ringbuffer_full(instance))
return false;
instance->data[instance->wr_pos] = item;
instance->wr_pos = (instance->wr_pos + 1) % instance->capacity;
if (instance->rd_pos == instance->wr_pos)
instance->full = true;
return true;
}
bool ringbuffer_dequeue(ringbuffer_t instance, uint8_t *item)
{
if (ringbuffer_empty(instance))
return false;
instance->full = false;
*item = instance->data[instance->rd_pos];
instance->rd_pos = (instance->rd_pos + 1) % instance->capacity;
return true;
}
void ringbuffer_destroy(ringbuffer_t instance)
{
if (instance) {
if (instance->data) {
free(instance->data);
}
free(instance);
}
}
void ringbuffer_debug(ringbuffer_t instance)
{
printf("%d/%d %d %d %s\n", ringbuffer_used(instance), ringbuffer_capacity(instance),
instance->wr_pos, instance->rd_pos, instance->full ? "(full)" : "");
}