matos/core/ringbuffer.c

88 lines
2.0 KiB
C
Raw Normal View History

#include "alloc.h"
#include "klibc.h"
#include "ringbuffer.h"
struct ringbuffer_instance_t {
int32_t wr_pos;
int32_t rd_pos;
uint8_t *data;
uint32_t capacity;
bool_t full;
};
ringbuffer_t ringbufferCreate(uint32_t capacity)
{
ringbuffer_t inst = zalloc(1* sizeof(struct ringbuffer_instance_t));
inst->data = zalloc(capacity * sizeof(uint8_t));
inst->capacity = capacity;
inst->wr_pos = 0;
inst->rd_pos = 0;
inst->full = capacity == 0;
return inst;
}
uint32_t ringbufferCapacity(ringbuffer_t instance)
{
return instance->capacity;
}
uint32_t ringbufferUsed(ringbuffer_t instance)
{
if (instance->full)
return instance->capacity;
return (instance->wr_pos - instance->rd_pos) % instance->capacity;
}
bool_t ringbufferEmpty(ringbuffer_t instance)
{
return (!instance->full && (instance->wr_pos == instance->rd_pos));
}
bool_t ringbufferFull(ringbuffer_t instance)
{
return instance->full;
}
bool_t ringbufferEnqueue(ringbuffer_t instance, uint8_t item)
{
if (ringbufferFull(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_t ringbufferDequeue(ringbuffer_t instance, uint8_t *item)
{
if (ringbufferEmpty(instance))
return FALSE;
instance->full = FALSE;
*item = instance->data[instance->rd_pos];
instance->rd_pos = (instance->rd_pos + 1) % instance->capacity;
return TRUE;
}
void ringbufferDestroy(ringbuffer_t instance)
{
if (instance) {
if (instance->data) {
free(instance->data);
}
free(instance);
}
}
void ringbufferDebug(ringbuffer_t instance)
{
printf("%d/%d %d %d %s\n", ringbufferUsed(instance), ringbufferCapacity(instance),
instance->wr_pos, instance->rd_pos, instance->full ? "(full)" : "");
}