Introduced ringbuf_init to perform static buffer initialisation

This commit is contained in:
EmergReanimator 2022-01-05 20:48:44 +01:00
parent 9a9893f3fc
commit da58c029a0
2 changed files with 16 additions and 5 deletions

View File

@ -27,11 +27,20 @@
#include "ringbuf.h"
bool ringbuf_init(ringbuf_t *r, uint8_t *buf, size_t capacity) {
r->heap = false;
r->buf = buf;
r->size = capacity + 1;
r->iget = r->iput = 0;
return r->buf != NULL;
}
// Dynamic initialization. This should be accessible from a root pointer.
// capacity is the number of bytes the ring buffer can hold. The actual
// size of the buffer is one greater than that, due to how the buffer
// handles empty and full statuses.
bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived) {
r->heap = true;
r->buf = gc_alloc(capacity + 1, false, long_lived);
r->size = capacity + 1;
r->iget = r->iput = 0;
@ -39,7 +48,10 @@ bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived) {
}
void ringbuf_free(ringbuf_t *r) {
gc_free(r->buf);
if (r->heap) {
gc_free(r->buf);
}
r->buf = (uint8_t *)NULL;
r->size = 0;
ringbuf_clear(r);
}

View File

@ -37,14 +37,13 @@ typedef struct _ringbuf_t {
uint32_t size;
uint32_t iget;
uint32_t iput;
bool heap;
} ringbuf_t;
// Note that the capacity of the buffer is N-1!
// Static initialization:
// byte buf_array[N];
// ringbuf_t buf = {buf_array, sizeof(buf_array)};
// For static initialization use ringbuf_init()
bool ringbuf_init(ringbuf_t *r, uint8_t *buf, size_t capacity);
bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived);
void ringbuf_free(ringbuf_t *r);
size_t ringbuf_capacity(ringbuf_t *r);